为了账号安全,请及时绑定邮箱和手机立即绑定

这是为什么?怎样可以使他从1号或者2号线程开始执行时也能全部执行完3个线程?

这是为什么?怎样可以使他从1号或者2号线程开始执行时也能全部执行完3个线程?

汪汪一只猫 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;}这个程序如果从0号线程开始执行的话就会将3个线程全都执行完,如果从1号或2号线程开始执行就会只执行一个线程之后就一直卡在那不动。
查看完整描述

1 回答

?
POPMUISE

TA贡献1765条经验 获得超5个赞

这段代码很容易死锁
如果1号线程先跑,他lock住mutex,这样其他线程是挂起的,但主线程在等着join 0号线程(顺序执行,先join0,再join1,如此下去),因为0线程此时为挂起,这样主线程也会挂起,而不可能跑去解锁mutex,发生死锁。
解决方法是把pthread_mutex_unlock放到线程里面去,线程创建时lock,线程退出时unlock

查看完整回答
反对 回复 2023-03-06
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信