为了账号安全,请及时绑定邮箱和手机立即绑定

作业社区

探索学习新天地,共享知识资源!

0 提交作业
0 布置作业
0 满分作业
得分 100
学习任务

weixin_慕哥3021856 的学生作业:

#include #include #include #include #include static int number = 0; static int total_of_produce = 0; static int total_of_consume = 0; static bool done = false; // 生产是否完成,默认否 static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond_produce = PTHREAD_COND_INITIALIZER; static pthread_cond_t cond_consume = PTHREAD_COND_INITIALIZER; void *thread_produce(void *arg) { int cnt = atoi((char *)arg); for (int i = 0; i < cnt; i++) { pthread_mutex_lock(&mtx); printf("生产者线程 [%ld] 生产1个产品,产品数量是 %d\n", pthread_self(), ++number); pthread_mutex_unlock(&mtx); pthread_cond_broadcast(&cond_consume); usleep(1000); } pthread_exit((void *)0); } void *thread_consume(void *arg) { while (1) { pthread_mutex_lock(&mtx); // 当产品数量为0时,阻塞线程并释放锁,这里设置循环是为了防止没有重新获得锁 while (number == 0 && !done) { pthread_cond_wait(&cond_consume, &mtx); } // 推出循环,结束线程 if (number == 0 && done) { pthread_mutex_unlock(&mtx); break; } if (number > 0) { total_of_consume++; printf("消费者 [%ld] 消费1个产品,产品数量是 %d\n", pthread_self(), --number); } pthread_mutex_unlock(&mtx); usleep(1000); } pthread_exit((void *)0); } int main(int argc, const char *argv[]) { int i = 0; int consume = 0, produce = 0; pthread_t tid; if (argc < 2) { fprintf(stderr, "Usage: %s producer1_num producer2_num ...\n", argv[0]); exit(EXIT_FAILURE); } // 创建生产者线程 pthread_t producers[argc-1]; pthread_t consumers[3]; // 3个消费者,固定数量 for (i = 1; i < argc; i++) { total_of_produce += atoi(argv[i]); produce = pthread_create(&producers[i-1], NULL, thread_produce, (void *)argv[i]); if (produce != 0) { perror("[ERROR] pthread_create()"); exit(EXIT_FAILURE); } } for (i = 0; i < 3; i++) { consume = pthread_create(&consumers[i], NULL, thread_consume, NULL); if (consume != 0) { perror("[ERROR] pthread_create()"); exit(EXIT_FAILURE); } } // 等待所有生产者完成 for (i = 0; i < argc - 1; i++) { pthread_join(producers[i], NULL); } // 设置生产完成标志,唤醒所有消费者 pthread_mutex_lock(&mtx); done = true; pthread_cond_broadcast(&cond_consume); pthread_mutex_unlock(&mtx); for (i = 0; i < 3; i++) { pthread_join(consumers[i], NULL); } printf("总共生产:%d,总共消费:%d\n", total_of_produce, total_of_consume); return 0; } 【图片】

微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号