第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

這是為什么?怎樣可以使他從1號(hào)或者2號(hào)線程開始執(zhí)行時(shí)也能全部執(zhí)行完3個(gè)線程?

這是為什么?怎樣可以使他從1號(hào)或者2號(hào)線程開始執(zhí)行時(shí)也能全部執(zhí)行完3個(gè)線程?

汪汪一只貓 2023-03-03 22:18:42
#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

查看完整回答
反對(duì) 回復(fù) 2023-03-06
  • 1 回答
  • 0 關(guān)注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)