File tree 1 file changed +59
-0
lines changed
1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include <pthread.h>
2
+ #include <stdio.h>
3
+ #include <unistd.h>
4
+
5
+ // Compile and link with -pthread
6
+
7
+ // Declaration of thread condition variable
8
+ pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER ;
9
+
10
+ // Declaring mutex
11
+ pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER ;
12
+
13
+ int done = 1 ;
14
+
15
+ void * create ();
16
+
17
+ int main ()
18
+ {
19
+ pthread_t tid1 , tid2 ;
20
+
21
+ // Create thread 1
22
+ pthread_create (& tid1 , NULL , create , NULL );
23
+
24
+ // Sleep for 1 sec so that thread 1
25
+ // would get a chance to run first
26
+ sleep (1 );
27
+
28
+ // Create thread 2
29
+ pthread_create (& tid2 , NULL , create , NULL );
30
+
31
+ // Wait for the completion of thread 2
32
+ pthread_join (tid2 , NULL );
33
+
34
+ return 0 ;
35
+ }
36
+
37
+ void * create ()
38
+ {
39
+ // Acquire a lock
40
+ pthread_mutex_lock (& lock );
41
+
42
+ if (done == 1 )
43
+ {
44
+ done = 2 ;
45
+ printf ("Waiting on condition variable cond1\n" );
46
+ pthread_cond_wait (& cond1 , & lock );
47
+ }
48
+ else
49
+ {
50
+ printf ("Signaling condition variable cond1\n" );
51
+ pthread_cond_signal (& cond1 );
52
+ }
53
+
54
+ // Release lock
55
+ pthread_mutex_unlock (& lock );
56
+ printf ("Returning thread\n" );
57
+
58
+ return NULL ;
59
+ }
You can’t perform that action at this time.
0 commit comments