亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么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 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號