[英]Understanding std::condition_variable
I refer to the accepted answer here: Using std::conditional_variable to wait on a condition and in particular the code (copied): 我在这里参考已接受的答案: 使用std :: conditional_variable等待条件 ,尤其是代码(已复制):
struct gate {
bool gate_open = false;
mutable std::condition_variable cv;
mutable std::mutex m;
void open_gate() {
std::unique_lock<std::mutex> lock(m);
gate_open=true;
cv.notify_all();
}
void wait_at_gate() const {
std::unique_lock<std::mutex> lock(m);
cv.wait( lock, [this]{ return gate_open; } );
}
};
I don't understand how this works as an event class. 我不明白这是如何作为事件类的。 How exactly does the code inside the mutex in open_gate
execute if something is already waiting via the wait_at_gate
functions. 究竟如何在互斥体的代码open_gate
执行,如果事情已经通过等待wait_at_gate
功能。 I'm guessing it has something to do with the std::condition_variable
. 我猜想它与std::condition_variable
。
OK, since no one is going to post, here's my answer, helped by the comments and the following links (from which quoted text is from, which slight modification for readability): 好的,因为没有人要发表,这是我的答案,这取决于评论和以下链接(引用文字来自何处,对可读性进行了一些修改):
http://en.cppreference.com/w/cpp/thread/condition_variable , http://en.cppreference.com/w/cpp/thread/condition_variable/wait , http://en.cppreference.com/w/cpp/thread/condition_variable/notify_all http://en.cppreference.com/w/cpp/thread/condition_variable , http://en.cppreference.com/w/cpp/thread/condition_variable/wait , http://en.cppreference.com/w/ cpp /线程/ condition_variable / notify_all
It assumes two threads, one, named OG
, calling open_gate()
and the other, named WG
, calling wait_at_gate()
. 它假定有两个线程,一个名为OG
,调用open_gate()
,另一个名为WG
,调用wait_at_gate()
。
1) Both functions are protected with locks, it is a requirement that "any thread that intends to wait on std::condition_variable
" acquires "a std::unique_lock<std::mutex>
, on the same mutex as used to protect the shared variable". 1)这两个函数都用锁保护,要求“打算在std::condition_variable
上等待的任何线程”都在与保护该对象相同的互斥std::unique_lock<std::mutex>
获取“ std::unique_lock<std::mutex>
”。共享变量”。
2) If OG
gets the lock first then it will open the gate before releasing the lock. 2)如果OG
首先获得锁,那么它将在释放锁之前打开门。 WG
then gets its lock, the gate is already opened. WG
随后将其锁上,门已经打开。 For this case since (from linked references): 对于这种情况,由于(来自链接的引用):
while (!pred()) {
wait(lock);
}
then there is no wait. 那就不用等待了。
3) If WG
gets its lock first then its call to cv.wait
"atomically releases the mutex and suspends the execution of the thread." 3)如果WG
首先获得其锁,则其对cv.wait
调用“以原子方式释放互斥并中止线程的执行”。
4) This allows OG
to proceed, which then sets the shared flag. 4)这允许OG
继续,然后设置共享标志。 WG
"will then be unblocked when notify_all()
is executed" by OG
. WG
“那么将当畅通notify_all()
通过执行” OG
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.