- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
在单独的主线程中执行相同的代码,条件变量的行为不同
#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 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/
有人可以向我澄清主线 DHT 规范中的声明吗? Upon inserting the first node into its routing table and when starting up th
我正在尝试使用 USB 小工具驱动程序使嵌入式设备作为 MTP 设备工作。 我知道 Android 从大容量存储设备切换到 MTP 设备已经有一段时间了,并且找到了 source code for M
我是一名优秀的程序员,十分优秀!