多线程同步 顺序打印数字 线程条件变量

先把条件变量函数甩出来,

//等待条件
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restric mutex);

1:把调用线程放到所等待条件的线程列表上
2:对传进来已经加过锁的互斥量解锁
3:线程进入休眠状态等待被唤醒
注:1、2步为原子操作


//通知条件
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t * cond);

1:通知指定条件已经满足
2:等待线程重新锁定互斥锁
3:等待线程需要重新测试条件是否满足


#include <pthread.h>
#include <iostream>
#include <stdlib.h>

using namespace std;
pthread_mutex_t g_mutex;
pthread_cond_t  g_cond;

static int num = 0;
void* thread1(void* id);
void* thread2(void* id);

int main(int argc,char* argv[])
{
	pthread_mutex_init(&g_mutex,NULL);
	pthread_cond_init(&g_cond,NULL);

	pthread_t id[2];
	
	pthread_create(&id[0],NULL,thread1,NULL);
	pthread_create(&id[1],NULL,thread2,NULL);

	pthread_join(id[0],NULL);
	pthread_join(id[1],NULL);
	
	pthread_cond_destroy(&g_cond);
	pthread_mutex_destroy(&g_mutex);
	
int c; 
	while((c =getchar()) != 'c')
	{
		sleep(1);
	}
	
	cout<< "exit process from main func" << endl;
	return 0;

}

void* thread1(void* id)
{
	while(1)
	{
		pthread_mutex_lock(&g_mutex);

		if(num % 2 == 1)
		{
			//enter wait will unlock resource and block current thread.
			//broadcast will active wait func
			pthread_cond_wait(&g_cond,&g_mutex);
			//end wait will lock resource
		}
		cout<< "thread 1 : " << num << endl; 
		++num;
		
		if(num > 10000)
		{
			pthread_cond_broadcast(&g_cond);
			pthread_mutex_unlock(&g_mutex);
			pthread_exit(0);	
		}	
		pthread_cond_broadcast(&g_cond);
		pthread_mutex_unlock(&g_mutex);
	}	
}


void* thread2(void* id)
{
	while(1)
	{
		pthread_mutex_lock(&g_mutex);

		if(num % 2 == 0)
		{
			pthread_cond_wait(&g_cond,&g_mutex);
		}
				
		if(num > 10000)
		{	
			pthread_mutex_unlock(&g_mutex);
			pthread_exit(0);
		}

		cout<< "thread 2 : " << num << endl; 
		++num;
		pthread_cond_broadcast(&g_cond);
		pthread_mutex_unlock(&g_mutex);
	}	
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值