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

为什么sleep位置改了也不行~ 如下改在解锁后面还是不行?

为什么sleep位置改了也不行~ 如下改在解锁后面还是不行?

陪伴而非守候 2023-04-15 22:18:51
#include <unistd.h>#include <pthread.h>#include <stdio.h>pthread_mutex_t Poll_Work;       //互斥pthread_cond_t Poll_Full;       //条件void* thread0(void *param){ while(*(int*)param < 100 && *(int*)param >= 0){ pthread_mutex_lock(&Poll_Work); (*(int*)param) += 5; printf("Thread0: %d\n", *(int*)param); pthread_mutex_unlock(&Poll_Work);                sleep(2); } pthread_cond_signal(&Poll_Full); return NULL; }void* thread1(void *param){ while(*(int*)param < 100 ){ pthread_mutex_lock(&Poll_Work); (*(int*)param) -= 5; printf("Thread1: %d\n", *(int*)param); pthread_mutex_unlock(&Poll_Work);                sleep(2); } pthread_cond_signal(&Poll_Full); return NULL; }void* thread2(void *param){ pthread_mutex_lock(&Poll_Work);  while(*(int*)param < 100)  pthread_cond_wait(&Poll_Full, &Poll_Work);  printf("Thread2: Poll Is Full!!\n");   pthread_mutex_unlock(&Poll_Work);  return NULL; }int main(){ int sum = 0;   //水深  满为100米 初始化 池里没有水 int i; pthread_mutex_init(&Poll_Work, NULL); pthread_cond_init(&Poll_Full, NULL); pthread_t ths[3]; pthread_create(&ths[0], NULL,  thread0, (void*)&sum); pthread_create(&ths[1], NULL,  thread1, (void*)&sum); pthread_create(&ths[2], NULL,  thread2, (void*)&sum); for(i = 0; i < 3; ++ i){ pthread_join(ths[i], NULL); } printf("Play End!\n"); }程序大概意思 一个可以装100水的pool 两个线程 一个不断加5 一个不断减3 第三个线程用于输出 当满的时候 输出Full 可是运行程序后 发现总是只有一个线程在运行 另一个完全没反应。 加了sleep也不见另一个线程被调度执行。
查看完整描述

1 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

因为你的sleep放错了地方,应该是放在 pthread_mutex_unlock 后面。

另外,不建议使用sleep,建议使用pthread_yield来放弃cpu。

然后你就会发现你的代码逻辑有些问题,比如说sum < 0了,thread1还在继续运行。


查看完整回答
反对 回复 2023-04-18
  • 1 回答
  • 0 关注
  • 76 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信