/* 编写一个程序, 创建两个线程, 一个线程负责生产产品, 另一个线程负责消费产品。要求实现线程间的同步和互斥, 确保生产者只在缓冲区未满时才能生产产品, 消费者只在缓冲区非空时才能消费产品。 */ #include #include #include // 互斥锁和条件变量初始化 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_p = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_c = PTHREAD_COND_INITIALIZER; int current = 0; int max = 100; int min = 0; void *producer(void *data) { while (1) { pthread_mutex_lock(&mutex); // 生产者加锁 while (current == max) { pthread_cond_wait(&cond_p, &mutex); } current++; printf("+++++++++++++++++++++生成者 %ld 完成生产, 仓库剩余 %d 个商品\n", pthread_self(), current); pthread_cond_broadcast(&cond_c); // 发出通知,让等待消费的线程恢复(条件满足) pthread_mutex_unlock(&mutex); // 生产者解锁 usleep(100 * 1000); } pthread_exit(NULL); } void *consumer(void *data) { while (1) { pthread_mutex_lock(&mutex); // 消费者加锁 while (current == min) { pthread_cond_wait(&cond_c, &mutex); } current--; printf("----------------------消费者 %ld 完成消费, 仓库剩余 %d 个商品\n", pthread_self(), current); pthread_cond_broadcast(&cond_p); pthread_mutex_unlock(&mutex); usleep(150 * 1000); } pthread_exit(NULL); } int main(int argc, char const *argv[]) { // 生产者线程 const int num_producer = 10; // 生产者数量 pthread_t t_producer[num_producer]; for (int i = 0; i < num_producer; i++) { pthread_create(&t_producer[i], NULL, producer, NULL); } // 消费者线程 const int num_consumer = 10; // 消费者数量 pthread_t t_consumer[num_consumer]; for (int i = 0; i < num_consumer; i++) { pthread_create(&t_consumer[i], NULL, consumer, NULL); } // join for (int i = 0; i < num_producer; i++) { pthread_join(t_producer[i], NULL); } for (int i = 0; i < num_consumer; i++) { pthread_join(t_consumer[i], NULL); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_c); pthread_cond_destroy(&cond_p); return 0; }