C++ Thread 信号量

信号量实现生产者消费者

int g_num = 0;
std::binary_semaphore semp(1);
std::binary_semaphore sems(0);

void P(int i)
{
	for (int i = 0; i < 10; ++i)
	{
		semp.acquire(); //1 -> 0    P操作
		g_num = i;
		cout << "P:" << g_num << endl;
		sems.release(); //0 -> 1    V操作
	}
}

void S()
{
	for (int i = 0; i < 20; ++i)
	{
		sems.acquire();
		cout << "S:" << g_num << endl;
		semp.release();
	}
}

int  main()
{
	thread tha(P, 1);
	thread thc(P, 2);
	thread thb(S);

	tha.join();
	thb.join();
	thc.join();

	return 0;
}
int g_num = 0;
std::counting_semaphore semp(2);
std::counting_semaphore sems(0);
std::mutex mx;

void P(int i)
{
	for (int i = 0; i < 10; ++i)
	{
		semp.acquire(); //1 -> 0    P操作
		mx.lock();
		g_num = i;  //防止g_num线程不完全
		mx.unlock();
		cout << "P:" << g_num << endl;
		sems.release(); //0 -> 1    V操作
	}
}

void S()
{
	for (int i = 0; i < 20; ++i)
	{
		sems.acquire();
		cout << "S:" << g_num << endl;
		semp.release();
	}
}

int  main()
{
	thread tha(P, 1);
	thread thc(P, 2);
	thread thb(S);

	tha.join();
	thb.join();
	thc.join();

	return 0;
}

MySemaphore

class MySemaphore
{
public:
	MySemaphore(int val = 1):count(val){}
	void P()  //acquire()
	{	
		std::unique_lock<std::mutex> lck(mtk);
		if (--count < 0) //资源不足
		{
			cv.wait(lck); //一旦唤醒则代表有资源
		}
	}
	void V()  //release()
	{
		std::unique_lock<std::mutex> lck(mtk);
		if (++count <= 0)
		{ 
			cv.notify_one();
		}
	}
	int get_count()
	{
		return count;
	}

private:
	int count;
	std::mutex mtk;
	std::condition_variable cv;
};

int g_num = 0;
MySemaphore semp(1);
MySemaphore sems(0);

std::mutex mx;
void P(int id)
{
	for (int i = 0; i < 10; ++i)
	{
		semp.P();  // p =  1 -> 0
		mx.lock();
		g_num = i;
		cout << "生产者:" << "  " << g_num << endl;
		mx.unlock();
		sems.V();  // s = 0 -> 1
	}
}
void S(int id)
{
	for (int i = 0; i < 10; ++i)
	{
		sems.P();
		mx.lock();
		cout << "消费者: " << ":" << g_num << endl;
		mx.unlock();
		semp.V();

	}
}

int main()
{
	std::thread tha(P, 0);
	std::thread ths(S, 0);

	tha.join();
	ths.join();

	return 0;
}
  1. 首先生产者线程进入,对生产者的信号量进行了一次P操作,生产者的信号量Pcount 1 -> 0 ,并且在最后将消费者的信号量Scount由0 -> 1
  2. 紧接消费者进入线程,进行一次P操作,消费者信号量Scount 1 -> 0,然后生产者的信号量进行一次V操作 Pcount 0 -> 1
  3. 倘若下一次进入的还是消费者,首先进行一次P操作,那么消费者Scount 0 -> -1 ,则消费者P操作进入等待队列
  4. 这时消费者的P操作陷入等待队列,只能由生产者进行P操作,则生产者信号量自减 Pcount 1 -> 0,接着将消费者进行V操作 Scount -1 -> 0 ,此时进行一次唤醒,将原本进入等待队列的消费者唤醒
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值