我无法理解conditional_variable
wait_for。
示例程序:
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
std::mutex m;
std::condition_variable cv;
bool ready = false;
using namespace std;
void worker_thread()
{
std::unique_lock<std::mutex> lk(m);
for (int i=0; i<3; i++) {
auto remaining = chrono::milliseconds::max();
std::cout << "Going to sleep for " << remaining.count() << endl;
bool r = cv.wait_for(lk, remaining, [] () { return ready;});
std::cout << "Wakey wakey " << r << endl;
}
std::cout << "Thread finished" << endl;
}
int main()
{
std::thread worker(worker_thread);
worker.join();
}
我希望这个程序能做什么:
ready
设为真,也未设为cv.notify_one()
它实际上做了什么:
Going to sleep for 9223372036854775807
Wakey wakey 0
Going to sleep for 9223372036854775807
Wakey wakey 0
Going to sleep for 9223372036854775807
Wakey wakey 0
Thread finished
这是因为“虚假的觉醒”吗?但我使用了文档中所述的重载(2)
:This overload may be used to ignore spurious awakenings.