Linux ptheard producer consumer, linuxptheard
1 # include <stdio. h>
2 # include <stdlib. h>
3 # include <pthread. h>
4
5 pthread_mutex_t mutex;
6 pthread_cond_t cond_full;
7 pthread_cond_t cond_empty;
8
9 int g_iBufSize = 0;
10
11 void * thread_producer (void * arg)
12 {
13 while (true)
14 {
15 printf ("thread_producer: pthread_mutex_lock \ n ");
16 pthread_mutex_lock (& mutex );
17 // you can access the lock without conflict, but the conditions may not be met. The cond is used to notify another process when the conditions are met.
18 if (0! = G_iBufSize) // if the condition is not met, the wait function is called and the waiting condition is met.
19 {
20 printf ("thread_producer: pthread_cond_wait cond_empty \ n ");
21 pthread_cond_wait (& cond_empty, & mutex); // the premise of this sentence is that there is a lock first, and at this time it will be automatically unlocked first, wait until the time comes to lock
22}
23
24 // The preceding wait operations already include shackles, which can be accessed directly here
25 printf ("thread_producer >>>>> \ n ");
26 g_iBufSize = 1;
27
28 printf ("thread_producer: pthread_cond_signal \ n ");
29 pthread_cond_signal (& cond_full );
30
31 pthread_mutex_unlock (& mutex );
32}
33 return NULL;
34}
35
36 void * thread_consumer (void * arg)
37 {
38 while (true)
39 {
40 printf ("thread_consumer: pthread_mutex_lock \ n ");
41 pthread_mutex_lock (& mutex );
42 if (0 = g_iBufSize)
43 {
44 printf ("thread_consumer: pthread_cond_wait \ n ");
45 pthread_cond_wait (& cond_full, & mutex );
46}
47
48 printf ("thread_consumer >>> \ n ");
49 g_iBufSize = 0;
50
51 printf ("thread_consumer: pthread_cond_signal \ n ");
52 pthread_cond_signal (& cond_empty );
53
54 pthread_mutex_unlock (& mutex );
55
56}
57 return NULL;
58}
59
60 // g ++-o bin1-lpthread mutithread. cpp
61
62 int main ()
63 {
64 void * retval1, * retval2;
65 pthread_t thread_id_1, thread_id_2;
66
67 pthread_mutex_init (& mutex, NULL );
68 pthread_cond_init (& cond_full, NULL );
69 pthread_cond_init (& cond_empty, NULL );
70
71 pthread_cond_signal (& cond_empty );
72 pthread_create (& thread_id_1, NULL, thread_producer, NULL); // int pthread_create (pthread_t * tidp, const pthread_attr_t * attr, (void *) (* start_rtn) (void *), void * arg );
73 pthread_create (& thread_id_2, NULL, thread_consumer, NULL );
74
75 pthread_join (thread_id_1, & retval1); // After the thread is blocked
76 pthread_join (thread_id_2, & retval2 );
77
78 pthread_cond_destroy (& cond_full );
79 pthread_cond_destroy (& cond_empty );
80 pthread_mutex_destroy (& mutex );
81
82 return 0;
83}