我对使用有点困惑std::condition_variable.我明白我必须创建unique_lock一个mutex调用之前condition_variable.wait().我无法找到是我是否也应该调用之前获得一个独特的锁notify_one()或notify_all().
cppreference.com上的示例存在冲突.例如,notify_one页面提供了以下示例:
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
std::condition_variable cv;
std::mutex cv_m;
int i = 0;
bool done = false;
void waits()
{
std::unique_lock<std::mutex> lk(cv_m);
std::cout << "Waiting... \n";
cv.wait(lk, []{return i == 1;});
std::cout << "...finished waiting. i == 1\n";
done = true;
}
void signals()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Notifying...\n";
cv.notify_one();
std::unique_lock<std::mutex> lk(cv_m);
i = 1;
while (!done) {
lk.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1)); …Run Code Online (Sandbox Code Playgroud) 我正在学习C++ 11并发性,其中我以前唯一的并发原语经验是六年前的操作系统类,所以如果可以,请保持温和.
在C++ 11中,我们可以编写
std::mutex m;
std::condition_variable cv;
std::queue<int> q;
void producer_thread() {
std::unique_lock<std::mutex> lock(m);
q.push(42);
cv.notify_one();
}
void consumer_thread() {
std::unique_lock<std::mutex> lock(m);
while (q.empty()) {
cv.wait(lock);
}
q.pop();
}
Run Code Online (Sandbox Code Playgroud)
这样可以正常工作,但我觉得需要包裹cv.wait一个循环.我们需要循环的原因对我来说很清楚:
Consumer (inside wait()) Producer Vulture
release the lock
sleep until notified
acquire the lock
I MADE YOU A COOKIE
notify Consumer
release the lock
acquire the lock
NOM NOM NOM
release the lock
acquire the lock
return from wait()
HEY WHERE'S MY COOKIE I EATED IT
Run Code Online (Sandbox Code Playgroud)
现在,我相信其中一个很酷的事情 …
我不知道如何在中间停止程序有人可以帮助我我希望我的程序停止定义的秒数,例如 3 秒或 6 秒,如果您按任意键,它会立即开始运行。