【发布时间】:2019-12-04 08:13:55
【问题描述】:
这个问题是关于condition_variable.wait()函数的。我认为它可能不会在收到通知时立即锁定unique_lock。让我展示我的代码,你会更好地理解我的测试。
注意:编译器 g++,std=c++14
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <atomic>
#include <future>
using namespace std;
mutex global_mut;
condition_variable global_cond;
atomic<bool> bval;
atomic<int> ival;
void accLock() {
unique_lock<mutex> lock(global_mut);
while (!bval.load()) {
global_cond.wait(lock);
}
cout << __PRETTY_FUNCTION__ << " get the lock" << endl;
ival.store(2, memory_order_release);
lock.unlock();
}
void getVal() {
lock_guard<mutex> lock(global_mut);
cout << __PRETTY_FUNCTION__ << " get the lock with " << ival.load(memory_order_acquire) << endl;
}
int main(int argc, char** argv) {
bval.store(false);
ival.store(0, memory_order_release);
// now my global_cond should be waiting for being notified
std::future<void> fut = std::async(std::launch::async, accLock);
// now my global_cond should be awaken and lock global_mut
bval.store(true);
global_cond.notify_one();
// getVal should be waiting for global_mut to be unlocked
getVal();
return 0;
}
理想情况下,我希望我的accLock 线程首先锁定互斥锁并更改ival,这样getVal() 可以加载最新的ival,即2。我希望看到类似的输出
void accLock() get the lock
void getVal() get the lock with 2
但实际上,这是
void getVal() get the lock with 0
void accLock() get the lock
显然,这个unique_lock 没有“立即”锁定在global_cond 中,而是让getVal() 中的lock_guard 首先获得互斥锁。
请问什么是实现我想要的正确方法?我对condition_variable 的理解是否正确?谢谢。
注意: 我使用 memory_order_acl 和 release 因为我认为这可以帮助我“纠正”订单。但它不起作用。
【问题讨论】:
标签: c++ multithreading mutex atomic condition-variable