modified: diffout.py
[GalaxyCodeBases.git] / c_cpp / pthreadtest / 04conditionexample.c
blob62c1ce5ddc04c126cd2f45e26e8f809f5cb7f554
1 /*
2 * cond.c
4 * Demonstrate a simple condition variable wait.
5 *
6 * to compile me for Linux, type: gcc -o conditionexample conditionexample.c -lpthread
7 */
8 #include <pthread.h>
9 #include <stdio.h>
10 #include <stdlib.h>
12 typedef struct {
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 */
16 } cond_struct_t;
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)
28 int status;
30 sleep (*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 ************/
45 return NULL;
48 int main (int argc, char *argv[])
50 int status;
51 pthread_t wait_thread_id;
52 struct timespec timeout;
53 int hibernation = 1;
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);
62 if (argc > 1)
63 hibernation = atoi (argv[1]);
66 * Create wait_thread.
68 status =
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
74 * the wait_thread.
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);
91 return 0;