From ffc2656985f9e8347cf44a0af343b9269fe32372 Mon Sep 17 00:00:00 2001 From: flykhan Date: Wed, 23 Aug 2023 00:24:34 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A4=9A=E4=BB=BB=E5=8A=A1=E4=BA=92=E6=96=A5?= =?UTF-8?q?=E4=B8=8E=E5=90=8C=E6=AD=A5(=E4=BA=92=E6=96=A5=E9=94=81,=20?= =?UTF-8?q?=E8=AF=BB=E5=86=99=E9=94=81,=20=E6=9D=A1=E4=BB=B6=E5=8F=98?= =?UTF-8?q?=E9=87=8F,=20=E4=BF=A1=E5=8F=B7=E9=87=8F,=20=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=BF=A1=E5=8F=B7=E9=87=8F):=20=E4=BD=9C=E4=B8=9A1,2,3,4,5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day7/homework/h5.c | 87 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 day7/homework/h5.c diff --git a/day7/homework/h5.c b/day7/homework/h5.c new file mode 100644 index 0000000..009a141 --- /dev/null +++ b/day7/homework/h5.c @@ -0,0 +1,87 @@ +/* +编写一个程序, 创建两个线程, 一个线程负责生产产品, 另一个线程负责消费产品。要求实现线程间的同步和互斥, 确保生产者只在缓冲区未满时才能生产产品, 消费者只在缓冲区非空时才能消费产品。 +*/ +#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; +}