【发布时间】:2016-11-06 04:13:28
【问题描述】:
我有以下场景:
condition_variable cv;
mutex mut;
// Thread 1:
void run() {
while (true) {
mut.lock();
// create_some_data();
mut.unlock();
cv.notify_all();
}
}
// Thread 2
void thread2() {
mutex lockMutex;
unique_lock<mutex> lock(lockMutex);
while (running) {
cv.wait(lock);
mut.lock();
// copy data
mut.unlock();
// process data
}
}
// Thread 3, 4... - same as Thread 2
我一直运行线程 1 来获取新数据。其他线程使用 condition_variable 等待,直到有新数据可用,然后复制它并对其进行一些工作。线程执行的工作在完成所需的时间上有所不同,其想法是线程只有在完成旧数据时才会获取新数据。同时获得的数据允许“遗漏”。我不使用共享互斥锁(仅用于访问数据),因为我不希望线程相互依赖。
上面的代码在 Windows 上运行良好,但现在我在 Ubuntu 上运行它,我注意到当 notify_all() 被调用时只有一个线程被通知,而其他线程只是挂在 wait() 上。 这是为什么? Linux 是否需要不同的方法来使用 condition_variable?
【问题讨论】:
-
I don't use shared mutex (only to access data) because I don't want threads to depend on each other.- 但是使用条件变量 需要 共享互斥锁。没有别的办法。
标签: c++ multithreading condition-variable