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 <assert.h> #include <pthread.h> #include <stdio.h>
int buffer; int count = 0; pthread_cond_t cond_consumer; pthread_cond_t cond_procedure; pthread_mutex_t mutex;
void put(int value) { assert(count == 0); count = 1; buffer = value; }
int get() { assert(count == 1); count = 0; return buffer; }
void *producer(void *arg) { int loops = *((int *)arg); for (int i = 0; i < loops; i++) { pthread_mutex_lock(&mutex); while (count == 1) { pthread_cond_wait(&cond_procedure, &mutex); } put(i); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond_consumer);
} return NULL; }
void *consumer(void *arg) { int loops = *((int *)arg); for (int i = 0; i < loops; i++) { pthread_mutex_lock(&mutex);
while (count == 0) { pthread_cond_wait(&cond_consumer, &mutex); } int temp = get(); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond_procedure); printf("消费:%d\n", temp); } return NULL; }
int main() {
pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond_consumer, NULL); pthread_cond_init(&cond_procedure, NULL);
pthread_t p1, p2, p3; int arg = 100; int arg1 = 50; int arg2 = 50; pthread_create(&p1, NULL, producer, &arg); pthread_create(&p2, NULL, consumer, &arg1); pthread_create(&p3, NULL, consumer, &arg2); pthread_join(p1, NULL); pthread_join(p2, NULL); pthread_join(p3, NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_consumer); pthread_cond_destroy(&cond_procedure); return 0; }
|