c++ - 条件变量的谓词

标签 c++ multithreading concurrency condition-variable

我是多线程新手。在使用条件变量在 C++11 中编写多线程代码时,我使用以下结构

while(predicate) {
    cond_var.wait(&lock);
}

但是,我一直在阅读 Deitel 关于操作系统的第三版书籍(第 6 章),其中使用了以下结构

if(predicate) {
    cond_var.wait(&lock);
}

那么,有什么区别呢?为什么这本书没有使用 while?虚假调用不是问题吗?

最佳答案

虚假唤醒始终是一个潜在的问题。例如,查看此处的答案:Do spurious wakeups actually happen? .也许 Deitel 的代码是一个更大的循环的一部分,可以帮助他们处理虚假唤醒?或者这可能只是一个错字。

在任何情况下,都没有(好的)理由不使用您的构造,事实上 wait 函数有一个变体可以为您完成它(http://en.cppreference.com/w/cpp/thread/condition_variable/wait)。

template< class Predicate >
void wait( std::unique_lock<std::mutex>& lock, Predicate pred );

相当于:

while (!pred()) {
     wait(lock);
}

关于c++ - 条件变量的谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22837254/

相关文章:

c++ - MS 蓝牙堆栈文档

c++ - 类成员函数与速度方面的函数

c++ - 在 Windows 内核设备驱动程序中使用 fprintf

c - Linux 中对 pthread_create 的 undefined reference

python - 如何在 Python 中停止循环线程?

python - 我怎样才能做一个多线程扭曲的python

python - 并发 psycopg2 postgres 选择查询的空结果

c++ - 你如何在 C++ 中实现协程

multithreading - 线程: When ones thread is running can you interact with the other?

c++ - mutex.lock 与 unique_lock