gpt4 book ai didi

c++ - wait_until 在主线程中的工作方式与主线程不同吗? C++

转载 作者:搜寻专家 更新时间:2023-10-31 00:50:16 25 4
gpt4 key购买 nike

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

#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 在主线程中的工作方式与主线程不同吗? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57989575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com