给定一个条件变量,允许多个线程一次读取,但只有一个线程写入

Allowing multiple threads to read at once given a condition variable, but only one thread writing

我有这样一种情况,我有多个线程从映射中读取,而该映射仅写入线程 A。问题是从映射中读取的多个线程每个都在映射中寻找唯一值以继续, 一个id.

“线程 A”

注意:Payload 是一个包含一些信息的简单结构


std::map<unsigned int, int> jobStatus;
std::mutex mutexJobStatus;
std::condition_variable cv;

...
void receiveJobs() {
    while(true) {
        ...
        Payload payload = ...; //receive payload 
        std::lock_guard<std::mutex> lg(mutexJobStatus);
        jobStatus.insert({ payload.jobid, payload.value });
        cv.notify_all(); //notify all waiting threads that they can read
    }
}
...

同时在客户端多线程中,线程正在等待

多线程客户端


unsigned int jobId = ...; // item in map this thread is looking for

auto jobTaken = jobStatus.find(jobId);
{
    std::unique_lock<std::mutex> ul(mutexJobStatus);
    //wait for item to become available in the map
    sced->cv.wait(ul, [jobId, &jobTaken] { jobTaken = jobStatus.find(jobId); return jobTaken != jobStatus.end(); }); 
}

... 
//continue

当有很多线程读取时,这段代码执行得非常慢。我认为这可能是因为每次读取时,它都会锁定互斥锁,导致过度读取的线程被暂停——而实际上应该允许多个线程同时读取。

我对 C++ 中的多线程还很陌生,我不确定如何解决这个问题。我使用的 mutexes/locks/condition_variables 类型正确吗?

对于实现这种并发读取但阻塞写入的最佳方式的任何建议,我将不胜感激,而这将是让这段代码更好地执行所必需的。 谢谢

因为

unsigned int jobId = ...; // item in map this thread is looking for
std::unique_lock<std::mutex> ul(mutexJobStatus);
auto jobTaken = jobStatus.find(jobId);
//wait for item to become available in the map
sced->cv.wait(ul, [jobId, &jobTaken] { jobTaken = jobStatus.find(jobId); return jobTaken != jobStatus.end(); });
...

... 应该是范围结束的地方。