4 int number = (int)arg;
5 int status;
6 int i;
7 char buffer[128] ;
8
9 for (i = 1; i <= iterations; i++) {
10 /*
11 * Every time each thread does 5000 interations, print
12 * a progress report.
13 */
14 if (i % 2000 == 0) {
15 sprintf (
16 buffer, 'Thread %02d: %d
',
17 number, i);
18 write (1, buffer, strlen (buffer));
19 }
20
21 sched_yield ();
22 }
23
24 return (void *)0;
25 }
26
27 int
28 main (int argc, char *argv[])
29 {
30 pthread_t threads[THREAD_COUNT];
31 pthread_attr_t detach;
32 int status;
33 void *result;
34 int i;
35
36 status = pthread_attr_init (&detach);
37 if (status != 0)
38 err_abort (status, 'Init attributes object');
39 status = pthread_attr_setdetachstate (
40 &detach, PTHREAD_CREATE_DETACHED);
41 if (status != 0)
42 err_abort (status, 'Set create-detached'); 43
44 for (i = 0; i< THREAD_COUNT; i++) {
45 status = pthread_create (
46 &threads[i], &detach, thread_routine, (void *)i);
47 if (status != 0)
48 err_abort (status, 'Create thread');
49 }
50
51 sleep (2);
52
53 for (i = 0; i < THREAD_COUNT/2; i++) {
54 printf ('Suspending thread %d.
', i);
55 status = thd_suspend (threads[i]);
56 if (status != 0)
57 err_abort (status, 'Suspend thread');
58 }
59
60 printf ('Sleeping ...
');
61 sleep (2);
62
63 for (i = 0; i < THREAD_COUNT/2; i++) {
64 printf ('Continuing thread %d.
', i);
65 status = thd_continue (threads[i]);
66 if (status != 0)
67 err_abort (status, 'Suspend thread');
68 }
69
70 for (i = THREAD_COUNT/2; i < THREAD_COUNT; i++) {
71 printf ('Suspending thread %d.
', i);
72 status = thd_suspend (threads[i]);
73 if (status != 0)
74 err_abort (status, 'Suspend thread');
75 }
76
77 printf ('Sleeping ...
');
78 sleep (2);
79
80 for (i = THREAD_COUNT/2; i < THREAD_COUNT; i++) {
81 printf ('Continuing thread %d.
', i);
82 status = thd_continue (threads[i]);
83 if (status != 0)
84 err_abort (status, 'Continue thread');
85 }
86
87 pthread_exit (NULL); /* Let threads finish */
88 }
¦ susp.c part 5 sampleprogram
6.6.4 sigwait and sigwaitinfo
int sigwait (const sigset_t *set, int *sig);
#ifdef _POSIX_REALTIME_SIGNALS
int sigwaitinfo (const sigset_t *set, siginfo_t *info);
int sigtimedwait (const sigset_t *set, siginfo_t *info, const struct timespec *timeout);
#endif
Always use sigwait
to work with asynchronous signals within threaded code.
Pthreads adds a function to allow threaded programs to deal with 'asynchronous' signals synchronously. That is, instead of allowing a signal to interrupt a thread at some arbitrary point, a thread can choose to receive a signal synchronously. It does this by calling sigwait
, or one of sigwait's siblings.