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
| #include<stdio.h> #include<stdlib.h> #include<pthread.h>
#define CAP 1000
int count = 0;
pthread_cond_t fill, empty; pthread_mutex_t lock;
void consumer() { pthread_mutex_lock(&lock); while(count == 0) { pthread_cond_wait(&fill,&lock); } count--; pthread_cond_signal(&empty); pthread_mutex_unlock(&lock); }
void producer() { pthread_mutex_lock(&lock); while(count == CAP) { pthread_cond_wait(&empty,&lock); } count++; pthread_cond_signal(&fill); pthread_mutex_unlock(&lock); }
void* product(void* arg) { printf("%s start\n", (char*)arg); for(int i = 0; i < CAP; i++) { producer(); } printf("%s end\n", (char*)arg); } void* consume(void* arg) { printf("%s start\n", (char*)arg); for(int i = 0; i < CAP; i++) { consumer(); } printf("%s end\n", (char*)arg); }
int main() { pthread_mutex_init(&lock, NULL); pthread_cond_init(&fill, NULL); pthread_cond_init(&empty, NULL); pthread_t t1,t2,t3; pthread_create(&t1, NULL, product, "A"); pthread_create(&t2, NULL, product, "B"); pthread_create(&t3, NULL, consume, "C"); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_join(t3, NULL); printf("end count is %d\n", count); return 0; }
|