14 * "interrupted" flag (the main thread's wait predicate) and signal a
15 * condition variable. The main thread will exit.
16 */
17 void *signal_waiter (void *arg)
18 {
19 int sig_number;
20 int signal_count = 0;
21 int status;
22
23 while (1) {
24 sigwait (&signal_set, &sig_number);
25 if (sig_number == SIGINT) {
26 printf ("Got SIGINT (%d of 5)\n", signal_count+l);
27 if (++signal_count >= 5) {
28 status = pthread_mutex_lock (&mutex);
29 if (status != 0)
30 err_abort (status, "Lock mutex");
31 interrupted = 1;
32 status = pthread_cond_signal (&cond);
33 if (status != 0)
34 err_abort (status, "Signal condition");
35 status = pthread_mutex_unlock (&mutex);
36 if (status != 0)
37 err_abort (status, "Unlock mutex");
38 break;
39 }
40 }
41 }
42 return NULL;
43 }
44
45 int main (int argc, char *argv[])
46 {
47 pthread_t signal_thread_id;
48 int status;
49
50 /*
51 * Start by masking the "interesting" signal, SIGINT in the
52 * initial thread. Because all threads inherit the signal mask
53 * from their creator, all threads in the process will have
54 * SIGINT masked unless one explicitly unmasks it. The
55 * semantics of sigwait requires that all threads (including
56 * the thread calling sigwait) have the signal masked, for
57 * reliable operation. Otherwise, a signal that arrives
58 * while the sigwaiter is not blocked in sigwait might be
59 * delivered to another thread.
60 */
61 sigemptyset (&signal_set);
62 sigaddset (&signal_set, SIGINT);
63 status = pthread_sigmask (SIG_BLOCK, &signal_set, NULL);
64 if (status != 0)
65 err_abort (status, "Set signal mask"); 66
67 /*
68 * Create the sigwait thread.
69 */
70 status = pthread_create (&signal_thread_id, NULL,
71 signal_waiter, NULL);
72 if (status != 0)
73 err_abort (status, "Create sigwaiter");
74
75 /*
76 * Wait for the sigwait thread to receive SIGINT and signal
77 * the condition variable.
78 */
79 status = pthread_mutex_lock (&mutex);
80 if (status != 0)
81 err_abort (status, "Lock mutex");
82 while (!interrupted) {
83 status = pthread_cond_wait (&cond,&mutex);
84 if (status != 0)
85 err_abort (status, "Wait for interrupt");
86 }
87 status = pthread_mutex_unlock (&mutex);
88 if (status != 0)
89 err_abort (status, "Unlock mutex");
90 printf ("Main terminating with SIGINT\n");
91 return 0;
92 }
6.6.5 SIGEV_THREAD