线程的条件控制实现线程的同步

在使用线程的时候,通常需要对多线程惊醒条件判断实现同步控制,这里就得用到与线程条件相关的API。即线程的等待和触发,注:条件变量使用前必须先初始化。
相关代码如下:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

// int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

int date=0;
pthread_mutex_t mutex;    //互斥锁相关变量
pthread_cond_t cound; 	 //定义线程条件变量

void* func1(void* arg)
{
	static int cnt=0;
	static char *p="th1 quit";
	printf("This is create thread;and thread ID:%ld\n",(unsigned long)pthread_self());
	printf("pream is :%d\n",*((int*)arg));
	pthread_mutex_lock(&mutex);
	while(1)
	{
		pthread_cond_wait(&cound,&mutex);   //线程等待触发
		printf("=============t1 run=============\n");
		printf("t1date=%d\n",date);
		date=0;
		sleep(1);
		if(cnt==10)
		{
			exit(1);
		}
		cnt++;

	}
}

void* func2(void* arg)
{
	static char *p="th1 quit";
	printf("This is create thread;and thread ID:%ld\n",(unsigned long)pthread_self());
	printf("pream is :%d\n",*((int*)arg));
	while(1)
	{
		printf("t2date=%d\n",date);
		pthread_mutex_lock(&mutex);
		date++;
		if(date==3)
		{
			pthread_cond_signal(&cound);   //线程触发,th1开始执行
		}
		pthread_mutex_unlock(&mutex);      //互斥锁打开
		sleep(1);
	}
}
int main()
{
	pthread_t th1;
	pthread_t th2;
	int pream=100;
	pthread_mutex_init(&mutex,NULL);    //初始化互斥锁
	pthread_cond_init(&cound,NULL);     //初始化条件变量
	int point1=pthread_create(&th1,NULL,func1,(void*)&pream);
	int point2=pthread_create(&th2,NULL,func2,(void*)&pream);
	if(point1==0)
	{
	//	printf("This is main thread,and mainthread ID is %ld\n",(unsigned long)pthread_self());
	}
	pthread_join(th1,NULL);
	pthread_join(th2,NULL);
	pthread_mutex_destroy(&mutex);   //销毁互斥锁
	pthread_cond_destroy(&cound);    //销毁条件变量
	return 0;
}

测试小技巧:
当代码需要做测试的时候,我们可以写一个shell脚本或者直接写出一个程序来控制要执行的代码执行多少遍,然后生成一个测试文件,以上文代码为例,我们可以写出一个程序:

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char** argv)
{
	int time=atoi(argv[1]);
	int i;
	for(i=0;i<time;i++)
	{
		system("./demo");
	}

	return 0;

}

然后调用它,dmoe4是上文文件名

 ./a.out 10 >>test.ret.txt &

上文代码就会执行十遍后保存在test.ret.txt文件中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值