c++ - wait_until 在主线程中的工作方式与主线程中的工作方式是否不同?由 小码哥发布于

标签 c++ multithreading c++11 condition-variable

在主线程中执行相同的代码,条件变量的行为不同

#include <iostream>
#include <condition_variable>
#include <mutex>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
using namespace std::chrono_literals;
void waits()
{
    std::mutex mCvMtx;
    std::condition_variable mCondVar;

   auto now = std::chrono::system_clock::now();

    std::unique_lock<std::mutex> lk(mCvMtx);
    if(mCondVar.wait_until(lk, now+ 3*1000ms) ==  cv_status::timeout)
    {
        cout << "Fire";
    }
    else
    {
        cout << "Condition variable notified ";
    }
    now = std::chrono::system_clock::now();
}

int main()
{

     std::thread t1(waits);
     t1.join(); 

    return 0;
}
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
using namespace std::chrono_literals;

int main()
{
     std::mutex mCvMtx;
    std::condition_variable mCondVar;

   auto now = std::chrono::system_clock::now();

    std::unique_lock<std::mutex> lk(mCvMtx);
    if(mCondVar.wait_until(lk, now+ 3*1000ms) ==  cv_status::timeout)
    {
        cout << "Fire";
    }
    else
    {
        cout << "Condition variable notified ";
    }
    now = std::chrono::system_clock::now();

    return 0;
}

我无法理解为什么在第一个示例中输出结果为“Fire”(因此 cv 没有收到通知,它等待我指示的时间),而在第二种情况下,我在主线程中执行相同的代码,输出结果为“通知条件变量”,无需等待任何秒。

你有什么解释吗?谢谢

最佳答案

这是因为 spurious wakeups

Spurious wakeup describes a complication in the use of condition variables as provided by certain multithreading APIs such as POSIX Threads and the Windows API.

Even after a condition variable appears to have been signaled from a waiting thread's point of view, the condition that was awaited may still be false. One of the reasons for this is a spurious wakeup; that is, a thread might be awoken from its waiting state even though no thread signaled the condition variable. For correctness it is necessary, then, to verify that the condition is indeed true after the thread has finished waiting. Because spurious wakeup can happen repeatedly, this is achieved by waiting inside a loop that terminates when the condition is true

进一步阅读:

C++ Core Guidelines: Be Aware of the Traps of Condition Variables

关于c++ - wait_until 在主线程中的工作方式与主线程中的工作方式是否不同?由 小码哥发布于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57989575/

相关文章:

C++ 私有(private)访问其他类的成员

c++ - 由于未调用 _ReadBarrier() 而导致错误的示例程序是什么?

c++ - std::atomic 的默认值是多少?

c++ - cpp 文件中的部分特化不是 "well-formed"

c++ - std::vector::reserve 是否保证在这种情况下实现不会使迭代器无效?

c++ - glUnproject 和重新绘制场景后的奇怪结果

c++ - resize() 和 reserve() 有什么区别?

multithreading - Linux 内核等待队列和列表之间的正确交互

c++ - c/c++ 自然语言处理库

c++ - 尝试学习类(class)和 'heap' c++