[英]How to wake up multiple threads using condition variable
I want to run multiple threads every 100ms.我想每 100 毫秒运行多个线程。 In order to achieve that I thought of introducing
std::mutex
and std::condition_variable
.为了实现这一点,我想到了引入
std::mutex
和std::condition_variable
。 The problem I'm facing is on what basis the threads should go into waiting state.我面临的问题是线程应该在什么基础上等待 state。 This is my current code
这是我当前的代码
std::mutex m;
std::condition_variable cv;
Timer_Thread.cpp Timer_Thread.cpp
while (true) {
std::lock_guard<std::mutex> LG(m);
cv.notify_all(); // notifies every 100ms
}
Thread1.cpp线程1.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
}
As you can see the threads are waiting without checking any predicate.如您所见,线程正在等待而不检查任何谓词。 Can somebody suggest any alternatives to achieve the same.
有人可以提出任何替代方案来实现相同的目标。 All I want is to notify multiple threads every 100ms simultaneously.
我想要的只是每 100 毫秒同时通知多个线程。
As you mentioned about spurious wake-ups, thus my solution is to use another variable flag to let the waked thread can distinguish the correct notified case and spurious waked up case.正如你提到的虚假唤醒,因此我的解决方案是使用另一个变量标志来让唤醒线程能够区分正确的通知情况和虚假唤醒情况。 So actually, what comes to my mind is semaphore.
所以实际上,我想到的是信号量。 The
counting_semaphore
needs c++20, but i think writing a similar naive semaphore in pre C++20 version by using condition_variable
and mutex
is not a hard thing to you. counting_semaphore
需要 c++20,但我认为使用condition_variable
和mutex
在 C++20 之前的版本中编写类似的幼稚信号量对您来说并不是一件难事。
std::counting_semaphore<MAX_THREAD_NUM> semaphore;
// Timer_Thread.cpp
while (true) {
semaphore.release(thread_num); // notifies every 100ms
}
// Thread1.cpp
// multiple threads should run every 100ms
while (true) {
semaphore.acquire();
// do rest of the work
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.