Boost scoped_lock使用Boost条件变量
Boost scoped_lock usage with boost condition variables
我正在尝试使用条件变量来实现从两个线程中按顺序打印数字,一个打印偶数,另一个打印奇数。
#include <iostream>
#include <boost/thread.hpp>
#include <condition_variable>
using namespace std;
boost::mutex m;
boost::condition_variable cv_even;
boost::condition_variable cv_odd;
bool even_done = false;
bool odd_done = false;
bool wait_main = true;
void odd_printer(){
cout<<"Start oddn";
int i = 0;
while(true){
boost::mutex::scoped_lock lock(m);
cout<<"Odd acquired lock " << i << endl;
while(!even_done) cv_odd.wait(lock);
if(i % 2 == 1){
cout<<i<<endl;
}
i++;
even_done = false;
odd_done = true;
cv_even.notify_one();
}
}
void even_printer(){
cout<<"Start evenn";
int i = 0;
while(true){
boost::mutex::scoped_lock lock(m);
cout<<"Even acquired lock " << i << endl;
while(!odd_done) cv_even.wait(lock);
if(i % 2 == 0){
cout<<i<<endl;
}
i++;
odd_done = false;
even_done = true;
cv_odd.notify_one();
cout<<"End scope evenn";
}
}
int main(){
boost::thread odd_t{odd_printer};
boost::thread even_t{even_printer};
sleep(2);
odd_done = true;
cv_even.notify_one();
odd_t.join();
even_t.join();
}
在sleep(2)
语句结束之前我得到的输出是:
Start even
Even acquired lock 0
Start odd
Odd acquired lock 0
两个线程如何获取互斥锁m上的锁?换句话说,语句boost::mutex::scoped_lock lock(m);
在两个线程中都经过。它们中的一个不应该等待另一个先释放互斥对象m上的锁吗?
工作方式是cv.wait(lock)
在返回之前解锁锁并再次锁定。这就是其他线程锁定并继续的方式。这就是为什么锁必须传递给wait-function的原因。
理想情况下,主程序应该在访问共享标志之前锁定。
相关文章:
- Boost Spirit x3 条件(三元)运算符解析器
- boost::asio::async_read_until 具有自定义匹配条件运算符重载混淆
- 有条件地使用 Boost Python 添加模块
- 使用 Boost::Spirit 解析前提条件和递归
- 在`boost ::条件:: TIMED_WAIT中消除`boost :: Xtime`
- boost::OSX 上 32 位和 64 位程序之间共享内存中的进程间同步机制(互斥体、条件)
- 带有boost ::条件_variable的僵局
- 在C 中处理Boost线程条件
- Boost Tribol导致C++中从右到左的条件求值
- boost::进程间消息队列创建时的竞争条件
- 带有原始指针的boost :: shared_ptr变量的条件初始化
- 在 boost::type_traits::条件中使用类型特征的编译错误
- 如果插槽对象包含互斥锁和条件变量,则 Boost signals2 connect() 调用编译失败
- boost::asio::async_read在不满足完成条件的情况下结束
- Boost::线程 / C++11 std::thread,想要唤醒工作线程的条件
- 如何使用 Boost Atomic 删除竞争条件
- 如何使用boost条件变量来等待线程完成处理
- Boost scoped_lock使用Boost条件变量
- boost条件不在具有两个生产者和一个消费者的线程安全队列上工作
- 带有多个线程的Boost条件变量