C++多线程-第五篇-同步机制

本文介绍C++中的条件变量及其应用,通过生产者与消费者的实例展示如何利用条件变量进行线程间的同步,包括通知与等待机制,并提供完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Call_once

使用call_once包装的函数在多线程中只会被执行一次。

Void call_once(once_flag&flag, Callable && func,Args &&.....args);

其中once_flag 声明必须是线程安全的,可采用static.且不可使用临时变量给Call_once.

 

 

条件变量--同步机制

需要和互斥量配合使用。

Thread中含有两种,condition_variable 和 condition_variable_any,

后者更常用并可以适应更广泛的互斥量类型。

类摘要

Enum  class cv_status{ no_timeout, timeout };	//等待状态
Class condition_variable_any
{
Public:
	Void notify_one();	//通知一个等待中的线程
	Void notify_all();	//通知所有等待

	Void wait(lock_type_&lock);	//等待
	Void wait(lock_type&lock,
		predicate_type predicate);	//条件等待

	Cv_status wait_for(lock_type&lock,
		Const duration& d);	//等待相对时间
	Cv_status wait_for(lock_type&lock,
		Const duration&d,
		Predicate_type predicate);	//条件等待相对时间
	Cv_status wait_until(lock_type&lock,
		Const time_point & t);	//等待绝对时间
	Cv_status wait_for(lock_type&lock,
		Const time_point & t,
		Predicate_type predicate);	//条件等待绝对时间
};


Code:(参考某Blog,忘记出处,Sorry)

#include<iostream>
#include<stack>
#include<boost/thread/thread.hpp>
#include<boost/thread/lock_factories.hpp>
using namespace std;
using namespace boost;

class buffer
{
private:
	mutex mu;							//配合条件变量
	condition_variable_any cond_put;
	condition_variable_any cond_get;
	stack<int> stk;
	int un_read, capacity;
	bool is_full()
	{
		return un_read == capacity;
	}
	bool is_empty()
	{
		return un_read == 0;
	}
public:
	buffer(size_t n) :un_read(0), capacity(n){}
	void put(int x)
	{
		{
			auto lock = make_unique_lock(mu);
			for (; is_full();)
			{
				cout << "full waiting ..." << endl;
				cond_put.wait(lock);	//条件变量等待
			}
			stk.push(x);
			++un_read;
		}
		cond_get.notify_one();
	}
	void get(int &x)
	{
		{
			auto lock = make_unique_lock(mu);
			for (; is_empty();)
			{
				cout << "empty waiting ..." << endl;
				cond_get.wait(lock);
			}
			--un_read;
			x = stk.top();
			stk.pop();
		}
		cond_put.notify_one();
	}
};

mutex mux;							//输出好看,,,,
buffer buf(5);
void producer(int n)
{
	for (int i = 0; i < n; i++)
	{
		mux.lock();
		cout << "put" << i << endl;
		mux.unlock();
		buf.put(i);

	}
}

void consumer(int n)
{
	int x;
	for (int i = 0; i < n; i++)
	{
		buf.get(x);
		mux.lock();
		cout << "get" << x << endl;
		mux.unlock();
	}
}

int main()
{
	//条件变量实现生产者与消费者模式	
	thread_group tg;
	tg.create_thread(bind(producer, 20));
	tg.create_thread(bind(consumer, 10));
	tg.create_thread(bind(consumer, 10));
	tg.join_all();
	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值