简体   繁体   English

boost :: condition_variable并锁定

[英]boost::condition_variable and lock

boost::condition_variable cond;
boost::mutex mut;

//thread1
{
"read_socket()"
cond.notify_one();
}

//thread2
{
for(;;)
{
...
boost::unique_lock<boost::mutex> lock(mut);
cond.wait(lock);
}
}

versus

boost::condition_variable cond;
boost::mutex mut;

//thread1
{
"read_socket()"
boost::unique_lock<boost::mutex> lock(mut);
cond.notify_one();
}

//thread2
{
for(;;)
{
...
boost::unique_lock<boost::mutex> lock(mut);
cond.wait(lock);
}

Is there an impact if I omit the lock before calling cond.notify_one() ? 如果在调用cond.notify_one()之前省略锁定会有影响吗?

The C++11 standard does not state any requirement for notify_one and notify_all ; C ++ 11标准没有规定对notify_onenotify_all任何要求; so not holding the lock when you signal a condition_variable is fine. 因此,当您发出condition_variable信号时,不要按住锁定。 However, it's often necessary for the signaling thread to hold the lock until it sets the condition checked by the waiting thread after it's woken up. 但是,信号线程通常需要保持锁定,直到它在唤醒之后设置由等待线程检查的条件为止。 If it does not, the program may contain races. 如果没有,该程序可能包含比赛。 For an example, see this SO question: Boost synchronization . 例如,请参阅此SO问题: 增强同步

When thread2 is waking, it will attempt to re-aquire the lock. thread2唤醒时,它将尝试重新获取锁。 If thread1 is holding the lock, thread2 will block until thread1 releases the lock. 如果thread1持有锁,则thread2将阻塞,直到thread1释放锁。

In the code shown here, this doesn't significantly impact behavior. 在此处显示的代码中,这不会显着影响行为。 If you were to add any behavior in thread1 after cond.notify_one(); 如果你在cond.notify_one();之后在thread1添加任何行为cond.notify_one(); , that behavior would be guaranteed to execute before thread2 proceeds in the second code block only. ,该行为将保证在thread2仅在第二个代码块中继续之前执行。

Alternatively, you could construct the unique lock in thread2 before entering the for loop, rather than just before waiting on the condition variable. 或者,您可以在进入for循环之前在thread2构造唯一锁,而不是在等待条件变量之前。 This would ensure that thread1 blocks when trying to construct its own unique lock until thread2 is waiting for a signal, provided that thread1 is not executing before thread2 has initialized itself and entered the loop. 这将确保thread1在尝试构造自己的唯一锁时阻塞,直到thread2等待信号,前提是thread1thread2初始化并进入循环之前没有执行。 This would allow you to guarantee that thread1 doesn't send any notifications that thread2 isn't waiting for. 这将允许您保证thread1不发送thread2不等待的任何通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM