14 * thread, each time the timer expires.
15 *
16 * When the timer has expired 5 times, the main thread will
17 * be awakened, and will terminate the program.
18 */
19 void
20 timer_thread (void *arg)
21 {
22 int status;
23
24 status = pthread_mutex_lock (&mutex);
25 if (status != 0)
26 err_abort (status, "Lock mutex");
27 if (++counter >= 5) {
28 status = pthread_cond_signal (&cond);
29 if (status != 0)
30 err_abort (status, "Signal condition");
31 }
32 status = pthread_mutex_unlock (&mutex);
33 if (status != 0)
34 err_abort (status, "Unlock mutex");
35
36 printf ("Timer %d\n", counter);
37 }
38
39 main( )
40 {
41 int status;
42 struct itimerspec ts;
43 struct sigevent se;
44
45 #ifdef sun
46 fprintf (
47 stderr,
48 "This program cannot compile on Solaris 2.5.\n"
49 "To build and run on Solaris 2.6, remove the\n"
50 "\"#ifdef sun\" block in main().\n");
51 #else
52 /*
53 * Set the sigevent structure to cause the signal to be
54 * delivered by creating a new thread.
55 */
56 se.sigev_notify = SIGEV_THREAD;
57 se.sigev_value.sival_ptr = &timer_id;
58 se.sigev_notify_function = timer_thread;
59 se.sigev_notify_attributes = NULL;
60
61 /*
62 * Specify a repeating timer that fires every 5 seconds.
63 */
64 ts.it_value.tv_sec = 5;
65 ts.it_value.tv_nsec = 0;
66 ts.it_interval.tv_sec = 5;
67 ts.it_interval.tv_nsec = 0;
68
69 DPRINTF (("Creating timer\n"));
70 status = timer_create(CLOCK_REALTIME, &se, &timer_id);
71 if (status == -1)
72 errno_abort ("Create timer");
73
74 DPRINTF ((
75 "Setting timer %d for 5-second expiration...\n", timer_id));
76 status = timer_settime(timer_id, 0, &ts, 0);
77 if (status == -1)
78 errno_abort ("Set timer");
79
80 status = pthread_mutex_lock (&mutex);
81 if (status != 0)
82 err_abort (status, "Lock mutex");
83 while (counter < 5) {
84 status = pthread_cond_wait (&cond, &mutex);
85 if (status != 0)
86 err_abort (status, "Wait on condition");
87 }
88 status = pthread_mutex_unlock (&mutex);
89 if (status != 0)
90 err_abort (status, "Unlock mutex");
91
92 #endif /* Sun */
93 return 0;
94 }
6.6.6 Semaphores: synchronizing with a signal-catching function
#ifdef _POSIX_SEMAPHORES
int sem_init (sem_t *sem, int pshared, unsigned int value);
int sem_destroy (sem_t *sem);
int sem_wait (sem_t*sem);
int sem_trywake (sem_t *sem);
int sem_post (sem_t *sem);
int sem_getvalue (sem_t *sem, int *sval);
#endif