经典的生产者消费者问题,在这里用信号量和互斥量来实现生产和消费者模型
1 |
<span style= "font-size: 15px;" > </span> |
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 |
#include<cstdlib> #include<cstdio> #include<unistd.h> #include<pthread.h> #include<semaphore.h> int t = 0; sem_t empty,full; pthread_mutex_t mutex; void * producer( void * arg){ int * time =( int *) arg; while ( true ){ sem_wait(&empty); pthread_mutex_lock(&mutex); //add t++; printf ( "producer add 1 to %d\n" , t); pthread_mutex_unlock(&mutex); sem_post(&full); sleep(* time ); } } void * customer( void * arg){ while ( true ){ sem_wait(&full); pthread_mutex_lock(&mutex); //delete t--; printf ( "customer delete 1 to %d\n" , t); pthread_mutex_unlock(&mutex); sem_post(&empty); sleep(4); } } int
main(){ pthread_t pthread_producer,pthread_producer_2; pthread_t pthread_customer; pthread_mutex_init(&mutex,NULL); sem_init(&full,0,0); sem_init(&empty,0,10); int
a = 2; int
b = 3; pthread_create(&pthread_producer,NULL,producer,&a); pthread_create(&pthread_producer_2,NULL,producer,&b); pthread_create(&pthread_customer,NULL,customer,NULL); pthread_join(pthread_customer,NULL); pthread_join(pthread_producer,NULL); pthread_join(pthread_producer_2,NULL); return
0; } |
1 |
|
pthread 实现生产者消费者问题,布布扣,bubuko.com
原文:http://www.cnblogs.com/clyskyblue/p/3572405.html