IO day7 (三id切换)

 1. 用条件变量的方式实现:现有ID号为a b c的三个线程,每个线程的任务都是循环打印自己id号,要求打印的顺序为abc

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>

int flag=1;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1=PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2=PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3=PTHREAD_COND_INITIALIZER;
void* bad1(void * arg)
{

	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(flag!=1)
		{
			pthread_cond_wait(&cond1,&mutex);
		}

		printf("tid1==》%ld\t",*(pthread_t *)arg);
		flag=2;

		pthread_cond_signal(&cond2);	
		pthread_mutex_unlock(&mutex);
	}	

	return NULL;
}

void* bad2(void * arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);

		if(flag!=2)
		{
			pthread_cond_wait(&cond2,&mutex);
		}

		printf("tid2==》%ld\t",*(pthread_t *)arg);
		flag=3;


		pthread_cond_signal(&cond3);	
		pthread_mutex_unlock(&mutex);

	}

	return NULL;
}

void* bad3(void * arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);

		if(flag!=3)
		{
			pthread_cond_wait(&cond3,&mutex);
		}

		printf("tid3==》%ld\n",*(pthread_t *)arg);
		flag=1;


		pthread_cond_signal(&cond1);	
		pthread_mutex_unlock(&mutex);

	}

	return NULL;
}

int main(int argc, const char *argv[])
{


	pthread_t tid1;
	pthread_t tid2;
	pthread_t tid3;
	//	int ttid1=pthread_create(&tid1,NULL,bad1,NULL);
	//	int ttid2=pthread_create(&tid2,NULL,bad2,NULL);
	int ttid1=pthread_create(&tid1,NULL,bad1,(void *)&tid1);
	int ttid2=pthread_create(&tid2,NULL,bad2,(void *)&tid2);
	int ttid3=pthread_create(&tid3,NULL,bad3,(void *)&tid3);
	//	printf("[1]%ld\t\t%d\n",tid1,ttid1);
	//	printf("[2]%ld\t\t%d\n",tid2,ttid2);
	if(ttid1)
	{
		fprintf(stderr,"pthread_creat is flase.%d\n",__LINE__);
		return -1;
	}
	pthread_detach(tid1);

	if(ttid2)
	{
		fprintf(stderr,"pthread_creat is flase.%d\n",__LINE__);
		return -1;
	}
	pthread_join(tid2,NULL);
	pthread_detach(tid2);

	if(ttid3)
	{
		fprintf(stderr,"pthread_creat is flase.%d\n",__LINE__);
		return -1;
	}
	pthread_join(tid3,NULL);
	pthread_detach(tid3);


	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond1);
	pthread_cond_destroy(&cond2);
	pthread_cond_destroy(&cond3);
	while(1)
		sleep(1);

	return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值