#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::packaged_task<int(void)> pt(mythread);
std::thread t(std::ref(pt));
t.join();
std::future<int> future = pt.get_future();
std::shared_future<int> sfuture(future.share());
/* 可用于多线程 */
std::cout << "shared_future " << sfuture.get() << std::endl;
std::cout << "shared_future " << sfuture.get() << std::endl;
return 0;
}
$ ./a.out
main 140470666590016
mythread 140470649251584
shared_future 5
shared_future 5