主线程设置等待时间,如果到时间就返回结果
#include<future>
#include<iostream>
#include<thread>
using namespace std;
void outStatus(std::future_status status) {
if (status == std::future_status::ready)
{
cout << "线程执行完" << endl;
}
else if (status == std::future_status::timeout)
{
cout << "线程超时" << endl;
}
else if (status == std::future_status::deferred)
{
cout << "线程延迟执行" << endl;
}
}
int myThread() {
cout << "Thread id " << this_thread::get_id() << "isstart" << endl;
this_thread::sleep_for(chrono::milliseconds(5s));
cout << "Thread id " << this_thread::get_id() << " isover" << endl;
return 5;
}
int middle() {
future<int> result = async(launch::async, myThread);
cout << "wait for\n";
future_status status = result.wait_for(std::chrono::milliseconds(3s));
outStatus(status);
cout << "wait over" << endl;
return 5;
}
int main() {
future<int> result = async(launch::async, middle);
int x; cin >> x;
}