#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;}這個(gè)程序如果從0號(hào)線程開始執(zhí)行的話就會(huì)將3個(gè)線程全都執(zhí)行完,如果從1號(hào)或2號(hào)線程開始執(zhí)行就會(huì)只執(zhí)行一個(gè)線程之后就一直卡在那不動(dòng)。
1 回答

POPMUISE
TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
這段代碼很容易死鎖
如果1號(hào)線程先跑,他lock住mutex,這樣其他線程是掛起的,但主線程在等著join 0號(hào)線程(順序執(zhí)行,先join0,再join1,如此下去),因?yàn)?線程此時(shí)為掛起,這樣主線程也會(huì)掛起,而不可能跑去解鎖mutex,發(fā)生死鎖。
解決方法是把pthread_mutex_unlock放到線程里面去,線程創(chuàng)建時(shí)lock,線程退出時(shí)unlock
添加回答
舉報(bào)
0/150
提交
取消