简体   繁体   English

C ++-如何不错过多个线程的多个通知?

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

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. 在代码中,task2通知了等待线程,但是等待线程waitForWork错过了通知。

#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");
}

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. 然后,您的工作线程必须在此队列上工作,并且不会再丢失任何通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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