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;
}
相关文章推荐
- 多进程多线程环境下的同步机制性能测试
- 【译】剖析MFC多线程程序的同步机制
- c++多线程例(事件同步对象,变量共享)
- 剖析MFC多线程程序的同步机制
- 多线程(C++)同步Semaphore
- C#的多线程机制探索(三)—线程的同步和通讯(生产者和消费者)
- Windows下C++的同步机制的演变
- 多线程编程同步机制之临界区编程实例
- Java分布式应用学习笔记03JVM对多线程的资源同步和交互机制
- c++中的异步和同步机制
- 【译】剖析MFC多线程程序的同步机制
- 剖析MFC多线程程序的同步机制
- linux 多线程和同步机制的使用
- 多线程编程同步机制之互斥量编程实例
- linux 多线程和同步机制的使用
- linux 多线程和同步机制的使用
- 转载 【译】剖析MFC多线程程序的同步机制
- (转)剖析MFC多线程程序的同步机制---译
- 多线程之旅之三——Windows内核对象同步机制
- 剖析MFC多线程程序的同步机制