1. 生产者1个线程
2. 消费者1个线程
3. 通过pthread_mutex_t并发控制
4. 通过pthread_cond_t wait signal
5. signal放到unlock后面
6. sleep放到unlock后面
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 | #include <stdio.h> #include <unistd.h> #include <pthread.h> #define PRODUCER_SIZE 1 #define CONSUMER_SIZE 1 int products = 0; pthread_mutex_t mutex; pthread_cond_t cond; void produce(); void consume(); int main() { pthread_t producer; pthread_t consumer; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_create(&producer, NULL, produce, NULL); pthread_create(&consumer, NULL, consume, NULL); pthread_join(producer, NULL); pthread_join(consumer, NULL); return 0; } void produce(){ // sleep(2); printf ( "start produce\n" ); while (1) { pthread_mutex_lock(&mutex); products++; printf ( "produce:%d start wake consum\n" , products); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); sleep(1); } } void consume() { printf ( "start consum\n" ); while (1) { pthread_mutex_lock(&mutex); while (products <= 0) { printf ( "consum start wait cond\n" ); pthread_cond_wait(&cond, &mutex); printf ( "consum wake up\n" ); } if (products > 0) { printf ( "consum:%d\n" , products); products --; } pthread_mutex_unlock(&mutex); sleep(3); } } |
02-14 04:05