wait_for函数
int threadEntryMethod()
{
std::cout << "this thread id si " << std::this_thread::get_id() << std::endl;
std::chrono::milliseconds dura(2000);
std::this_thread::sleep_for(dura);
std::cout << "this thread workd finished" << std::endl;
return 666;
}
int main()
{
std::future<int> myFuture = std::async(threadEntryMethod);
std::future_status myFutureStatus = myFuture.wait_for(std::chrono::seconds(1));
}
wait_for函数返回值 std::future_status的应用
int threadEntryMethod()
{
std::cout << "this thread id si " << std::this_thread::get_id() << std::endl;
std::chrono::milliseconds dura(2000);
std::this_thread::sleep_for(dura);
std::cout << "this thread workd finished" << std::endl;
return 666;
}
int main()
{
std::future<int> myFuture = std::async(std::launch::deferred,threadEntryMethod);
std::future_status myFutureStatus = myFuture.wait_for(std::chrono::seconds(1));
if (myFutureStatus == std::future_status::timeout)
{
std::cout << "子线程执行超时" << std::endl;
}
else if (myFutureStatus == std::future_status::ready)
{
std::cout << "子线程正常执行完毕" << std::endl;
}
else if (myFutureStatus == std::future_status::deferred)
{
std::cout << "子线程被延迟执行" << std::endl;
int result = myFuture.get();
std::cout << "在defer中,执行结果是 " << result << std::endl;
}
return 0;
}
std::future只能get一次的问题=>std::shared_future
#include <iostream>
#include <thread>
#include <future>
void threadEntryMethod1(std::promise<int> &myPromise,int i)
{
std::cout << "子线程id是 " <<std::this_thread::get_id() << std::endl;
int result = i * 100;
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
myPromise.set_value(result);
}
void threadEntryMethod2(std::shared_future<int> &myFuture)
{
std::cout << "子线程id是 " << std::this_thread::get_id() << std::endl;
int result = myFuture.get();
std::cout << "执行结果时" << result << std::endl;
}
int main()
{
std::cout << "主线程id是 " << std::this_thread::get_id() << std::endl;
std::promise<int> myPromise;
std::thread myThread(threadEntryMethod1,std::ref(myPromise), 6);
std::future<int> myFuture = myPromise.get_future();
std::shared_future<int> mySharedFuture(std::move(myFuture));
int result1 = mySharedFuture.get();
int result2 = mySharedFuture.get();
std::cout << result1 << std::endl;
std::cout << result2 << std::endl;
myThread.join();
std::thread myThread2(threadEntryMethod2,std::ref(mySharedFuture));
myThread2.join();
std::cout << "the main thread is finished" << std::endl;
}