我有一种情况,我有多个线程从只在线程a中写入的映射中读取。问题是,从映射中读取的多个线程都在映射中寻找一个唯一的值来继续
"线程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++中的多线程还相当陌生,我不确定如何解决这个问题。我是否使用了正确类型的互斥锁/条件变量?
我将感谢任何关于实现这种并发读取但阻止写入的最佳方法的建议,这将是使代码更好地执行所必需的。感谢
这是因为
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(); });
...
具有...
,其中应该是作用域的末尾。