#include <pthread.h>#include <stdio.h>#include <stdlib.h>#define THREAD_NUMBER 3#define REPEAT_NUMBER 3#define DELAY_TIME_LEVELS 10.0pthread_mutex_t mutex;void *thrd_func(void *arg){int thrd_num = (int)arg;int delay_time = 0,count =0;int res;res = pthread_mutex_lock(&mutex);if(res){printf("Thread %d lock failed\n",thrd_num);pthread_exit(NULL);}printf("Thread %d is starting\n",thrd_num);for(count = 0;count <REPEAT_NUMBER;count++){delay_time = (int)(rand() * DELAY_TIME_LEVELS/(RAND_MAX))+1;sleep(delay_time);printf("\tThread %d: job %d delay = %d\n",thrd_num,count,delay_time);}printf("Thread %d finished\n",thrd_num);pthread_exit(NULL);}int main(){pthread_t thread[THREAD_NUMBER];int no = 0, res;void * thrd_ret;srand(time(NULL));pthread_mutex_init(&mutex,NULL);for(no = 0;no<THREAD_NUMBER;no++){res = pthread_create(&thread[no],NULL,thrd_func,(void *)no);if(res != 0){printf("Create thread %d failed\n",no);exit(res);}}printf("Creat threads success\n Waiting for threads to finish...\n");for(no=0;no<THREAD_NUMBER;no++){res = pthread_join(thread[no],&thrd_ret);if(!res){printf("Thread %d joined\n",no);}else{printf("Thread %d join failed\n",no);}pthread_mutex_unlock(&mutex);}pthread_mutex_destroy(&mutex);return 0;}這個程序如果從0號線程開始執行的話就會將3個線程全都執行完,如果從1號或2號線程開始執行就會只執行一個線程之后就一直卡在那不動。
1 回答

POPMUISE
TA貢獻1765條經驗 獲得超5個贊
這段代碼很容易死鎖
如果1號線程先跑,他lock住mutex,這樣其他線程是掛起的,但主線程在等著join 0號線程(順序執行,先join0,再join1,如此下去),因為0線程此時為掛起,這樣主線程也會掛起,而不可能跑去解鎖mutex,發生死鎖。
解決方法是把pthread_mutex_unlock放到線程里面去,線程創建時lock,線程退出時unlock
- 1 回答
- 0 關注
- 99 瀏覽
添加回答
舉報
0/150
提交
取消