Day 6请使用互斥锁 和 信号量分别实现5个线程之间的同步

互斥锁

//创建锁
pthread_mutex_t m1;
pthread_mutex_t m2;
pthread_mutex_t m3;
pthread_mutex_t m4;
pthread_mutex_t m5;
 
void *task1(void *arg)
{
	while(1)
	{
		pthread_mutex_lock (&m1);
		printf("线程1\n");
		sleep(1);
		pthread_mutex_unlock (&m2);
	}
}
 
void *task2(void *arg)
{
	while(1)
	{
		pthread_mutex_lock (&m2);
		printf("线程2\n");
		sleep(1);
		pthread_mutex_unlock (&m3);
	}
}
 
void *task3(void *arg)
{
	while(1)
	{
		pthread_mutex_lock (&m3);
		printf("线程3\n");
		sleep(1);
		pthread_mutex_unlock (&m4);
	}
}
 
void *task4(void *arg)
{
	while(1)
	{
		pthread_mutex_lock (&m4);
		printf("线程4\n");
		sleep(1);
		pthread_mutex_unlock (&m5);
	}
}
 
void *task5(void *arg)
{
	while(1)
	{
		pthread_mutex_lock (&m5);
		printf("线程5\n");
		sleep(1);
		pthread_mutex_unlock (&m1);
	}
}
 
int main(int argc, const char *argv[])
{//请使用互斥锁 和 信号量分别实现5个线程之间的同步	
	//初始化锁
	pthread_mutex_init(&m1,NULL);
	pthread_mutex_init(&m2,NULL);
	pthread_mutex_init(&m3,NULL);
	pthread_mutex_init(&m4,NULL);
	pthread_mutex_init(&m5,NULL);
	//上锁分支线程中的锁
	pthread_mutex_lock(&m2);
	pthread_mutex_lock(&m3);
	pthread_mutex_lock(&m4);
	pthread_mutex_lock(&m5);
	//创建线程id
	pthread_t id1,id2,id3,id4,id5;
	//创建线程
	pthread_create(&id1,0,task1,0);
	pthread_create(&id2,0,task2,0);
	pthread_create(&id3,0,task3,0);
	pthread_create(&id4,0,task4,0);
	pthread_create(&id5,0,task5,0);
	//设置分离属性
	pthread_detach(id1);
	pthread_detach(id2);
	pthread_detach(id3);
	pthread_detach(id4);
	pthread_detach(id5);
 
	task1(NULL);
	return 0;
}

信号量

//创建信号量变量
sem_t s1;
sem_t s2;
sem_t s3;
sem_t s4;
sem_t s5;
 
void *task1(void *arg)
{
	while(1)
	{
		sem_wait (&s1);
		printf("线程1\n");
		sleep(1);
		sem_post (&s2);	
	}
}
 
void *task2(void *arg)
{
	while(1)
	{
		
		sem_wait (&s2);
		printf("线程2\n");
		sleep(1);	
		sem_post (&s3);	
	}
}
 
void *task3(void *arg)
{
	while(1)
	{
		sem_wait (&s3);
		printf("线程3\n");
		sleep(1);
		sem_post (&s4);
	}
}
 
void *task4(void *arg)
{
	while(1)
	{
		sem_wait (&s4);
		printf("线程4\n");
		sleep(1);
		sem_post (&s5);
	}
}
 
void *task5(void *arg)
{
	while(1)
	{
		sem_wait (&s5);
		printf("线程5\n");
		sleep(1);
		sem_post(&s1);
		
	}
}
 
int main(int argc, const char *argv[])
{//请使用互斥锁 和 信号量分别实现5个线程之间的同步	
	//初始化信号量
	sem_init(&s1,0,1);
	sem_init(&s2,0,0);
	sem_init(&s3,0,0);
	sem_init(&s4,0,0);
	sem_init(&s5,0,0);
	
	//创建线程id
	pthread_t id1,id2,id3,id4,id5;
	//创建线程
	pthread_create(&id1,0,task1,0);
	pthread_create(&id2,0,task2,0);
	pthread_create(&id3,0,task3,0);
	pthread_create(&id4,0,task4,0);
	pthread_create(&id5,0,task5,0);
	//设置分离属性
	pthread_detach(id1);
	pthread_detach(id2);
	pthread_detach(id3);
	pthread_detach(id4);
	pthread_detach(id5);
 
	task1(NULL);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值