【发布时间】:2022-01-19 07:12:32
【问题描述】:
我想每 100 毫秒运行多个线程。为了实现这一点,我想到了引入std::mutex 和std::condition_variable。我面临的问题是线程应该在什么基础上进入等待状态。这是我当前的代码
std::mutex m;
std::condition_variable cv;
Timer_Thread.cpp
while (true) {
std::lock_guard<std::mutex> LG(m);
cv.notify_all(); // notifies every 100ms
}
Thread1.cpp
// multiple threads should run every 100ms
while (true) {
std::unique_lock<std::mutex> UL(m);
cv.wait(UL);
UL.unlock();
// do rest of the work
}
如您所见,线程正在等待而不检查任何谓词。有人可以提出任何替代方案来实现相同的目标。我想要的只是每 100 毫秒同时通知多个线程。
【问题讨论】:
-
如果您不想要虚假唤醒,则需要添加一个额外的标志来检查
wait的谓词。您在寻找什么样的替代方案?这种方法对您不起作用的原因是什么? -
@user17732522 就像你说的虚假唤醒。有时线程甚至在 100 毫秒超时之前就开始运行。
标签: c++ mutex condition-variable