有一个使用 condition_variable
的例子来自 cppreference.com :
#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <queue>
#include <chrono>
int main()
{
std::queue<int> produced_nums;
std::mutex m;
std::condition_variable cond_var;
bool done = false;
bool notified = false;
std::thread producer([&]() {
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::lock_guard<std::mutex> lock(m);
std::cout << "producing " << i << '\n';
produced_nums.push(i);
notified = true;
cond_var.notify_one();
}
std::lock_guard<std::mutex> lock(m);
notified = true;
done = true;
cond_var.notify_one();
});
std::thread consumer([&]() {
while (!done) {
std::unique_lock<std::mutex> lock(m);
while (!notified) { // loop to avoid spurious wakeups
cond_var.wait(lock);
}
while (!produced_nums.empty()) {
std::cout << "consuming " << produced_nums.front() << '\n';
produced_nums.pop();
}
notified = false;
}
});
producer.join();
consumer.join();
}
如果在消费者线程启动之前变量done
变为true
,消费者线程将不会收到任何消息。事实上,sleep_for(seconds(1))
几乎可以避免这种情况,但是理论上是否可行(或者如果没有sleep
在代码中)?
在我看来,正确的版本应该是这样的,以强制至少运行一次消费者循环:
std::thread consumer([&]() {
std::unique_lock<std::mutex> lock(m);
do {
while (!notified || !done) { // loop to avoid spurious wakeups
cond_var.wait(lock);
}
while (!produced_nums.empty()) {
std::cout << "consuming " << produced_nums.front() << '\n';
produced_nums.pop();
}
notified = false;
} while (!done);
});
最佳答案
是的,您完全正确:有一种(远程)可能性,消费者线程只有在 done
设置之后才会开始运行。此外,生产者线程中对done
的写入和消费者线程中的读取会产生竞争条件,并且行为未定义。你的版本也有同样的问题。在 each 函数中将互斥体包裹在整个循环中。抱歉,没有精力编写正确的代码。
关于c++ - 了解使用 std::condition_variable 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733887/