#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不是应该交替输出的么?
1 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
unlock之后休眠一下
pthread_mutex_unlock(&mutex); /*释放互斥锁*/
sleep(1);
pthread1 start running!
pthread2 start running!
gnum=:1
gsub=:99
gnum=:2
gsub=:98
gnum=:3
gsub=:97
gnum=:4
gsub=:96
gnum=:5
- 1 回答
- 0 关注
- 58 浏览
添加回答
举报
0/150
提交
取消