-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path互斥锁条件变量协调生产和消费.c
83 lines (65 loc) · 1.58 KB
/
互斥锁条件变量协调生产和消费.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
int i, flag;
pthread_mutex_t mutex;
pthread_cond_t cond;
void gameover( int sig )
{
flag = 1;
pthread_cond_signal( &cond );
}
/*线程一,生产者*/
void *f1( void *arg )
{
while( !flag )
{
pthread_mutex_lock( &mutex );
/*当i等于10后给消费者发送信号,并停止生产*/
if( i == 10 )
{
pthread_cond_signal( &cond );
pthread_cond_wait( &cond, &mutex );
}
printf("now in thread1, i = %d\n", ++i );
usleep( 600000 );
pthread_mutex_unlock( &mutex );
}
pthread_exit( NULL );
}
/*线程二,消费者*/
void *f2( void *arg )
{
/*假如消费者先抢到锁了,就解锁并等待生产者发送信号*/
pthread_mutex_lock( &mutex );// 阻塞
pthread_cond_wait( &cond, &mutex );//
pthread_mutex_unlock( &mutex );
while( !flag )
{
pthread_mutex_lock( &mutex );
/*当i等于0后给生产者发送信号,并停止消费*/
if( i < 1 )
{
pthread_cond_signal( &cond );
pthread_cond_wait( &cond, &mutex );
}
printf(" now in thread2, i = %d\n", --i );
usleep( 600000 );
pthread_mutex_unlock( &mutex );
}
pthread_exit( NULL );
}
int main( void )
{
pthread_t pid1, pid2;
pthread_mutex_init( &mutex, NULL );
pthread_cond_init( &cond, NULL );
pthread_create( &pid1, NULL, f1, NULL );
pthread_create( &pid2, NULL, f2, NULL );
signal( SIGINT, gameover );
pthread_join( pid1, NULL );
pthread_join( pid2, NULL );
pthread_mutex_destroy( &mutex );
pthread_cond_destroy( &cond );
return 0;
}