1 # include <stdio. h>
2 # include <stddef. h>
3 # include <pthread. h>
4 # include <unistd. h>
5 Int I = 1;
6 pthread_mutex_t mutex;
7 pthread_cond_t cond;
8
9 void * task1 ()
10 {
11 For (I = 1; I <9; I ++)
12 {
13 pthread_mutex_lock (& mutex );
14 if (I % 3! = 0) printf ("in the task1: % d \ n", I );
15 else pthread_cond_signal (& Cond );
16 pthread_mutex_unlock (& mutex );
17 sleep (1 );
18}
19 return NULL;
20}
21
22 void * task2 ()
23 {
24 while (I <9)
25 {
26 pthread_mutex_lock (& mutex );
27 if (I % 3! = 0)
28 pthread_cond_wait (& cond, & mutex); // The end of Task 2 is always in the wait state because I = 8.
29
30 printf ("in the task2: \ t % d \ n", I );
31 pthread_mutex_unlock (& mutex );
32 sleep (1 );
33}
34 return NULL;
35
36}
37
38
39 int main ()
40 {
41 pthread_t t_id1, t_id2;
42 int succ;
43
44 pthread_mutex_init (& mutex, null );
45 pthread_cond_init (& cond, null );
46
47 succ = pthread_create (& t_id1, null, task1, null );
48 if (succ) {printf ("Failure in create thread! \ N "); return NULL ;}
49
50 succ = pthread_create (& t_id2, null, task2, null );
51 if (succ) {printf ("Failure in create thread2! \ N "); return NULL ;}
52
53 pthread_join (t_id1, null );
54 pthread_join (t_id2, null );
55
56 pthread_mutex_destroy (& mutex );
57 pthread_cond_destroy (& Cond );
58 return NULL;
59}
When using pthread_cond_wait (), you need to consider whether the program will exit when it is in the waiting state. When the above program I = 8, it will remain in the waiting state.
Solution 1: When setting conditions, make the process of wait not waiting during the last call;
Solution 2: Use pthread_cond_timedwait ()