Linux——线程中信号量和互斥量的运用

利用互斥量和信号量对创建的多个线程之间的调度进行控制
如果不进行控制,就会有多个线程同时获取到同一个数据,并对其进行操作。
例如让多个线程打印1-1000,不加锁有可能会打印两个相同的数。

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<pthread.h>
#include<semaphore.h>

int g = 1;
sem_t sem;
pthread_mutex_t mutex;//创建互斥锁

void* fun(void*arg)
{
	int i = 0;
	for(;i<1000;i++)
	{
		//sem_wait(&sem);//使用信号量进行的p操作
		pthread_mutex_lock(&mutex);
		printf("g=%d\n",g++);
		//sem_post(&sem);//使用信号量进行的V操作
		pthread_mutex_unlock(&mutex);
	}
}

int main()
{
	pthread_t id[5];
	//sem_init(&sem,0,1);//初始化信号量
	pthread_mutex_init(&mutex,NULL);//初始化锁
	int i = 0;
	for(;i<5.i++)
	{
		pthread_create(&id[i],NULL.fun.NULL);//创建线程
	}
	for(i = 0;i<5;i++)
	{
		pthread_join(id[i],NULL);//获取结束线程id
	}
	//sem_destroy(&sem);
	pthread_mutex_destroy(&mutex);//销毁锁
	exit(0);
}

循环打印ABC
使用三个线程sem1,sem2,sem3分别打印ABC,使用信号量控制打印顺序

在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<pthread.h>
#include<semaphore.h>

sem_t sem1;
sem_t sem2;
sem_t sem3;
void*fun_A(void* arg)
{
	int i = 0;
	for(;i<5;i++)
	{
		sem_wait(&sem1);//P操作
		wirte(1,"A",1);
		sem_post(&sem2);//V操作
	}
}
void* fun_B(void* arg)
{
	int i = 0;
	for(;i<5;i++)
	{
		sem_wait(&sem2);
		write(1,"B",1);
		sem_post(&sem3);
	}
}
void* fun_C(void* arg)
{
	int i = 0;
	for(;i<5;i++)
	{
		sem_wait(&sem3);
		write(1,"C",1)
		sem_post(&sem1);
	}
}


int main()
{
	pthread_t id[3];
	sem_init(&sem1,0,1);
	sem_init(&sem2,0,0);
	sem_init(&sem3,0,0);
	pthread_create(&id[0],NULL,fun_A,NULL);
	pthread_create(&id[1],NULL,fun_B,NULL);
	pthread_create(&id[2],NULL,fun_C,NULL);
	pthread_join(id[0],NULL);
	phtread_join(id[1],NULL);
	pthread_join(id[2],NULL);
	sem_destroy(&sem1);
	sem_destroy(&sem2);
	sem_destroy(&sem3);
	exit(0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有头发的小小猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值