#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還在繼續運行。
- 1 回答
- 0 關注
- 146 瀏覽
添加回答
舉報
0/150
提交
取消