繁体   English   中英

如何使用条件变量唤醒多个线程

[英]How to wake up multiple threads using condition variable

我想每 100 毫秒运行多个线程。 为了实现这一点,我想到了引入std::mutexstd::condition_variable 我面临的问题是线程应该在什么基础上等待 state。 这是我当前的代码

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
}

线程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
}

如您所见,线程正在等待而不检查任何谓词。 有人可以提出任何替代方案来实现相同的目标。 我想要的只是每 100 毫秒同时通知多个线程。

正如你提到的虚假唤醒,因此我的解决方案是使用另一个变量标志来让唤醒线程能够区分正确的通知情况和虚假唤醒情况。 所以实际上,我想到的是信号量。 counting_semaphore需要 c++20,但我认为使用condition_variablemutex在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM