4 * Demonstrate a simple condition variable wait.
6 * to compile me for Linux, type: gcc -o conditionexample conditionexample.c -lpthread
13 pthread_mutex_t mutex
; /* Protects access to value */
14 pthread_cond_t cond
; /* Signals change to value */
15 int value
; /* Access protected by mutex */
18 cond_struct_t data
= {
19 PTHREAD_MUTEX_INITIALIZER
, PTHREAD_COND_INITIALIZER
, 0};
23 * Thread start routine. It will set the main thread's predicate
24 * and signal the condition variable.
26 void * wait_thread (int *hibernation
)
32 /****** ENTER THE MONITOR HERE *******/
33 status
= pthread_mutex_lock (&data
.mutex
);
34 if (status
!= 0) {fprintf(stderr
,"Lock error!\n"); exit(-1);}
36 data
.value
= 1; /* Set predicate */
38 status
= pthread_cond_signal (&data
.cond
);
39 if (status
!= 0) {fprintf(stderr
,"Signal error!\n"); exit(-1);}
41 status
= pthread_mutex_unlock (&data
.mutex
);
42 if (status
!= 0) {fprintf(stderr
,"Unlock error!\n"); exit(-1);}
43 /******* EXIT the MONITOR ************/
48 int main (int argc
, char *argv
[])
51 pthread_t wait_thread_id
;
52 struct timespec timeout
;
56 * If an argument is specified, interpret it as the number
57 * of seconds for wait_thread to sleep before signaling the
58 * condition variable. You can play with this to see the
59 * condition wait below time out or wake normally.
61 //thr_setconcurrency(2);
63 hibernation
= atoi (argv
[1]);
69 pthread_create (&wait_thread_id
, NULL
, (void *) wait_thread
, &hibernation
);
70 if (status
!= 0) {fprintf(stderr
,"Create error!\n"); exit(-1);}
73 * Wait on the condition variable until signaled by
77 /***** ENTER the MONITOR HERE **********/
78 status
= pthread_mutex_lock (&data
.mutex
);
79 if (status
!= 0) {fprintf(stderr
,"Lock error!\n"); exit(-1);}
81 while (data
.value
== 0) {
82 status
= pthread_cond_wait(&data
.cond
, &data
.mutex
);
84 if (status
!= 0) {fprintf(stderr
,"Wait error!\n"); exit(-1);}
86 status
= pthread_mutex_unlock (&data
.mutex
);
87 if (status
!= 0) {fprintf(stderr
,"Unlock error!\n"); exit(-1);}
88 /******* EXIT the MONITOR **************/
90 printf("Condition was signalled, data.value=%d\n",data
.value
);