#include #include #include #include pthread_cond_t pcond; pthread_cond_t ccond; pthread_mutex_t mutex; struct Node{ int num; struct Node* next; }; struct Node* head = NULL; int cnt = 0; void* producer(void* arg); void* consumer(void* arg); int main(int argc, char const *argv[]) { pthread_cond_init(&pcond, NULL); pthread_cond_init(&ccond, NULL); pthread_mutex_init(&mutex, NULL); pthread_t t1[5], t2[5]; for (size_t i = 0; i < 5; i++) { pthread_create(&t1[i], NULL, producer, NULL); } for (size_t i = 0; i < 5; i++) { pthread_create(&t2[i], NULL, consumer, NULL); } for (size_t i = 0; i < 5; i++) { pthread_join(t1[i], NULL); pthread_join(t2[i], NULL); } pthread_cond_destroy(&pcond); pthread_cond_destroy(&ccond); pthread_mutex_destroy(&mutex); return 0; } void* producer(void* arg){ while(1){ pthread_mutex_lock(&mutex); while(cnt > 20){ pthread_cond_wait(&pcond, &mutex); } struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); //newNode->num = rand() % 1000; newNode->num = cnt++; newNode->next = head; head = newNode; printf("生产者 - id: %lu num: %d\n", pthread_self(), newNode->num); pthread_mutex_unlock(&mutex); pthread_cond_signal(&ccond); sleep(rand()%3); } return NULL; } void* consumer(void* arg){ while(1){ pthread_mutex_lock(&mutex); // 这里最好不要用if判断,可能出现并发处理问题,因为被唤醒的线程都会在pthread_cond_wait处等待唤醒,如果是if条件,在唤醒出继续往下执行时可能遇到head又为空的情况 // 需要用while循环再判断一次head是否为空,如果为空,pthread_cond_wait将继续阻塞线程 while(head == NULL){ pthread_cond_wait(&ccond, &mutex); } struct Node* node = head; printf("\t\t消费者 - id: %lu num: %d\n", pthread_self(), node->num); head = head->next; free(node); cnt--; pthread_mutex_unlock(&mutex); pthread_cond_signal(&pcond); sleep(rand()%6); } return NULL; }