版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hffhjh111/article/details/53141590
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;
-
}