您的位置:首页 > 编程语言 > C语言/C++

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

2016-11-12 16:46 441 查看

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: