使用条件变量时,http://en.cppreference.com/w/cpp/thread/condition_variable将通知线程的典型步骤描述为:
- acquire a std::mutex (typically via std::lock_guard)
- perform the modification while the lock is held
- execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification)
下面这个简单的例子,主线程在修改的时候是否需要锁定“stop”?虽然我知道在修改共享数据时锁定几乎总是一个好主意,但我不确定为什么在这种情况下有必要。
std::condition_variable cv;
std::mutex mutex;
bool stop = false;
void worker() {
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [] { return stop; })
}
// No lock (Why would this not work?)
void main() {
std::thread(worker);
std::this_thread::sleep_for(1s);
stop = true;
cv.notify_one();
}
// With lock: why is this neccesary?
void main() {
std::thread mythread(worker);
std::this_thread::sleep_for(1s);
{
std::unique_lock<std::mutex>(mutex);
stop = true;
}
cv.notify_one();
mythread.join();
}
最佳答案
For the simple case shown below, is it necessary for the main thread to lock "stop" when it modifies it?
是的,为了防止竞争条件。除了可以通过 std::atomic
解决的从不同线程访问共享数据的问题之外,想象一下以下事件顺序:
worker_thread: checks value of `stop` it is false
main_thread: sets `stop` to true and sends signal
worker_thread: sleeps on condition variable
在这种情况下,工作线程可能会永远休眠并且它会错过 stop
设置为 true
的事件,这仅仅是因为唤醒信号已经发送但它错过了。
在修改共享数据时获取互斥量是必需的,因为只有这样你才能将检查条件并进入休眠状态或在工作线程中对其进行操作作为一个整体的原子操作。
关于c++ - 通知线程是否总是需要在修改期间锁定共享数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47356463/