条件变量

条件变量

P V
二元信号量(不是零就是一)

binary_semaphore  semp=1;
binary_semaphore  sems=1;
semp.acquire();1->0
sems.release();0->1;

生产者与消费者

class MySemaphore//实现P操作和V操作
{
public:
	MySemaphore(int val=1):count(1){}
	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();
		}

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

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

void P(int id)//生产者
{
	for (int i = 0;i < 10;++i)
	{

		semp.P();
		{
			g_num = i;
			cout << "P : " << g_num << endl;
			std::this_thread::sleep_for(std::chrono::milliseconds(200));
			
		}
		sems.V();
	}
}
void S(int id)//消费者
{
	for (int i = 0;i < 10;++i)
	{
		sems.P();
		{
			
			std::this_thread::sleep_for(std::chrono::milliseconds(200));
			cout << "S : " << g_num << endl;
		}
		semp.V(); 
	}
}

int main()
{
	std::thread tha(P,1);
	std::thread ths(S,1);
	tha.join();
	ths.join();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值