C++ wait_for
作者:互联网
#include <iostream>
#include <future>
int mythread()
{
std::cout << "mythread " << std::this_thread::get_id() << std::endl;
std::chrono::milliseconds second(3000);
std::this_thread::sleep_for(second);
return 5;
}
int main()
{
std::cout << "main " << std::this_thread::get_id() << std::endl;
std::future<int> ret = std::async(std::launch::async, mythread);
std::future_status status = ret.wait_for(std::chrono::seconds(2));
switch(status)
{
case std::future_status::timeout:
std::cout << "timeout" << std::endl;
break;
case std::future_status::ready:
std::cout << "ready" << std::endl;
break;
case std::future_status::deferred:
std::cout << "deferred" << std::endl;
break;
default:
break;
}
std::cout << "future " << ret.get() << std::endl;
std::cout << "end" << std::endl;
return 0;
}
$ g++ wait_for.cpp -std=c++11 -pthread
$ ./a.out
main 140534331926336
mythread 140534314587904
timeout
future 5
end
std::future_status status = ret.wait_for(std::chrono::seconds(4));
$ ./a.out
main 140365530023744
mythread 140365512685312
ready
future 5
end
std::future<int> ret = std::async(std::launch::deferred, mythread);
$ ./a.out
main 140412357789504
deferred
mythread 140412357789504
future 5
end
标签:std,status,C++,mythread,future,ret,wait 来源: https://www.cnblogs.com/zhangxuechao/p/16563063.html