为什么线程1输出到50被挂起后线程2才会获得互斥锁呢?

#include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <errno.h> int gnum = 0; int gsub = 100;pthread_mutex_t mutex; pthread_cond_t cond; //条件变量 void pthread_func_1 (void); void pthread_func_2 (void); int main (void) { pthread_t pt_1 = 0; pthread_t pt_2 = 0; int ret = 0; pthread_mutex_init (&mutex, NULL); //默认情况下 互斥初始化后是解锁状态可用 pthread_cond_init(&cond,NULL); // //pthread_cond_init(指向pthread_cond_t的指针,属性设置<NULL>默认属性) ret = pthread_create (&pt_1, NULL, (void *)pthread_func_1, NULL); if (ret != 0) printf("pthread_1_create"); ret = pthread_create (&pt_2, NULL, (void *)pthread_func_2, NULL); if (ret != 0) printf("pthread_2_create"); pthread_join (pt_1, NULL); pthread_join (pt_2, NULL); printf ("main programme exit!/n"); return 0; }  
void pthread_func_1 (void) { //int i = 0; printf ("pthread1 start running!\n"); while(gnum <= 100) { pthread_mutex_lock(&mutex); /*注意,这里以防线程的抢占,以造成一个线程在另一个线程sleep时多次访问互斥资源,所以sleep要在得到互斥锁后调用*/ sleep (1); while (gnum == 50) { printf("supend thread1!!!\n"); pthread_cond_wait(&cond, &mutex); printf("thread1 restart!!!\n"); gnum++; } gnum++; printf ("gnum=:%d\n",gnum); pthread_mutex_unlock(&mutex); /*释放互斥锁*/ } }  
void pthread_func_2 (void) { printf ("pthread2 start running!\n"); while (gsub >= 0) { pthread_mutex_lock(&mutex);//mutex被锁住后,线程在此被挂起,等待mutex变为解锁状态后,获得互斥锁,继续执行 sleep (1); gsub--; printf ("gsub=:%d\n",gsub); if (gsub == 50) { printf("resume thread1 at gsun = 5\n"); pthread_cond_signal(&cond);//让挂起的线程继续执行 } pthread_mutex_unlock(&mutex); } pthread_exit (0); } 
线程1和线程2不是应该交替输出的么?

HUH函数
浏览 48回答 1
1回答

慕盖茨4494581

unlock之后休眠一下pthread_mutex_unlock(&mutex); /*释放互斥锁*/&nbsp;&nbsp;sleep(1);pthread1 start running!&nbsp;&nbsp;pthread2 start running!&nbsp;&nbsp;gnum=:1&nbsp;&nbsp;gsub=:99&nbsp;&nbsp;gnum=:2&nbsp;&nbsp;gsub=:98&nbsp;&nbsp;gnum=:3&nbsp;&nbsp;gsub=:97&nbsp;&nbsp;gnum=:4&nbsp;&nbsp;gsub=:96&nbsp;&nbsp;gnum=:5
打开App,查看更多内容
随时随地看视频慕课网APP