我已经实现了一个示例程序来了解 wait_for 和 wait_until 在 C++11 中是如何工作的。
代码 -
#include <iostream>
#include <future>
#include <chrono>
#include <mutex>
#include <condition_variable>
#include <thread>
using namespace std;
using namespace std::chrono;
condition_variable cv;
mutex m;
bool flagValue=false;
int sampleFunction(int a)
{
cout<<"Executing sampleFunction...";
cout.flush();
this_thread::sleep_for(seconds(5));
cout<<"Done."<<endl;
return a;
}
void sampleFunctionCond(int a)
{
lock_guard<mutex> lg(m);
cout<<"Executing sampleFunctionCond...";
cout.flush();
this_thread::sleep_for(seconds(5));
cout<<"Done."<<endl;
cout<<"Value : "<<a<<endl;
flagValue=true;
cv.notify_one();
return;
}
int main()
{
unique_lock<mutex> ul(m);
future<int> f1=async(launch::async,sampleFunction,10);
future_status statusF1=f1.wait_for(seconds(1));
if(statusF1==future_status::ready)
cout<<"Future is ready"<<endl;
else if (statusF1==future_status::timeout)
cout<<"Timeout occurred"<<endl;
else if (statusF1==future_status::deferred)
cout<<"Task is deferred"<<endl;
cout<<"Value : "<<f1.get()<<endl;
cv_status statusF2;
thread t1(sampleFunctionCond,20);
t1.detach();
while(!flagValue)
{
statusF2=cv.wait_until(ul,system_clock::now()+seconds(2));
if(statusF2==cv_status::timeout)
{
cout<<"Timeout occurred."<<endl;
break;
}
else
{
cout<<"Condition variable is ready or spurious wake up occurred."<<endl;
}
}
}
输出 -
Executing sampleFunction...Timeout occurred
Done.
Value : 10
Executing sampleFunctionCond...Done.
Value : 20
Timeout occurred.
sampleFunction 正在按预期工作,因为它在“完成”之前打印“发生超时”,但 sampleFunctionCond 的情况并非如此。虽然它知道 wait_until 已超时,但它会在函数 sampleFunctionCONd 完成执行后打印消息。
有人可以帮我理解吗?谢谢。