栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ Thread 信号量

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ Thread 信号量

信号量
  • 信号量实现生产者消费者
  • MySemaphore

信号量实现生产者消费者
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 lck(mtk);
		if (--count < 0) //资源不足
		{
			cv.wait(lck); //一旦唤醒则代表有资源
		}
	}
	void V()  //release()
	{
		std::unique_lock 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 ,此时进行一次唤醒,将原本进入等待队列的消费者唤醒
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847376.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号