我是条件变量的新手,我想知道为什么计数器变量等于 99 之后的这段代码块? 删除for循环并改用“counter += 99”使代码工作,它与sleep_for有什么关系吗?感谢您的帮助:)
#include<thread>
#include<condition_variable>
#include<mutex>
#include<chrono>
#include <iostream>
std::condition_variable cv;
std::mutex mtx;
int counter = 0;
void foo() {
std:: unique_lock<std::mutex>lck{ mtx };
//counter += 99;
for (; counter < 100; counter++) {
std::cout << counter << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
lck.unlock();
cv.notify_one();
}
int main() {
std::thread th(&foo);
{
std::unique_lock<std::mutex>lck{ mtx };
cv.wait(lck, [] {
return counter == 99;
});
}
std::cout << "!!!!!" << std::endl;
th.join();
}
最佳答案
让我们为您的代码添加一些注释:
void foo() {
std:: unique_lock<std::mutex>lck{ mtx };
// counter == 0
for (; counter < 100; counter++) {
...
}
// counter == 100
lck.unlock();
cv.notify_one(); // <== notify here
}
我们循环直到 counter == 100
,此时我们通知cv
.然而,我们正在等待counter == 99
,在收到通知时并非如此。 wait()
的唯一方法在您的代码中返回是为了在循环的最后一次迭代时发生虚假唤醒。
也许你打算循环 while counter < 99
.
关于c++ - 为什么在此代码块中使用 condition_variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32615223/