【问题标题】:How to wake up multiple threads using condition variable如何使用条件变量唤醒多个线程
【发布时间】:2022-01-19 07:12:32
【问题描述】:

我想每 100 毫秒运行多个线程。为了实现这一点,我想到了引入std::mutexstd::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


【解决方案1】:

正如你提到的虚假唤醒,因此我的解决方案是使用另一个变量标志来让唤醒线程能够区分正确的通知情况和虚假唤醒情况。所以实际上,我想到的是信号量。 counting_semaphore 需要 c++20,但我认为在 C++20 之前的版本中使用 condition_variablemutex 编写类似的幼稚信号量对你来说并不是一件难事。

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
}

【讨论】:

    猜你喜欢
    • 2011-05-02
    • 2011-08-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    相关资源
    最近更新 更多