簡體   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