C++ - How not to miss multiple notifications from multiple threads?

偶尔善良 提交于 2019-12-31 06:57:27

问题


In my application, many threads notify a waiting thread. Sometimes these notifications are very close to each other in time and the waiting thread misses the notification. Is there any easy way to counter this issue? A small example code is given below. In the code, the task2 notifies the waiting thread but the waiting thread, waitingForWork, miss the notification.

#include <condition_variable>
#include <iostream>
#include <thread>

std::mutex mutex_;
std::condition_variable condVar;

bool dataReady{ false };

void waitingForWork() {
    for (int i = 0; i < 2; i++)
    {
        std::cout << "Waiting " << std::endl;
        std::unique_lock<std::mutex> lck(mutex_);
        condVar.wait(lck, [] { return dataReady; });
        dataReady = false;
        std::cout << "Running " << std::endl;
    }
}

void task1() {
    std::this_thread::sleep_for(std::chrono::milliseconds{ 45 });
    std::lock_guard<std::mutex> lck(mutex_);
    dataReady = true;
    std::cout << "Task1 Done:" << std::endl;
    condVar.notify_one();

}

void task2() {
    std::this_thread::sleep_for(std::chrono::milliseconds{ 46 });
    std::lock_guard<std::mutex> lck(mutex_);
    dataReady = true;
    std::cout << "Task2 Done" << std::endl;
    condVar.notify_one();
}

int main() {

    std::cout << std::endl;

    std::thread t1(waitingForWork);               
    std::thread t2(task1);                 
    std::thread t3(task2);                 

    t1.join();
    t2.join();
    t3.join();

    std::cout << std::endl;
    system("pause");
}

回答1:


It's a multiple producer single consumer problem. Which is described here: Multiple consumer single producer problem

So basically you have to change your code in a way that each thread have to write notifications into a threadsafe queue. And then your worker thread has to work on this queue and will not miss anymore notifications.



来源:https://stackoverflow.com/questions/51784797/c-how-not-to-miss-multiple-notifications-from-multiple-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!