1. std::p romise can be used to provide data transfer between threads.
std::future = std::p romise.get_future ().
Promise can be assigned to a thread in std::p romise.set_value.
After the assignment, Std::future.get () returns the value set in the other thread.
#include<iostream>#include<future>#include<chrono>std::p romise<int>promis;intMainintargcConst Char*argv[]) {Std::future<int> Furesult =promis.get_future (); Std::thread T ([] () {std::this_thread::sleep_for (Std::chrono::seconds (Ten)); Promis.set_value (123); }); T.detach (); Std::cout<<"Detach ..."<<Std::endl; Std::cout<<furesult.Get() <<Std::endl; return 0;}
2. std::packaged_task can wrap a function, somewhat similar to std::function, except that this can get the result of a function executed asynchronously by Get_future returning the Std::future object.
#include <iostream>#include<future>#include<chrono>intMainintargcConst Char*argv[]) {std::p ackaged_task<int() >m ([] () {std::this_thread::sleep_for (Std::chrono::seconds (Ten)); return 123; }); Std::future<int> Furesult =m.get_future (); Std::thread Task (Std::move (m)); Task.detach (); Std::cout<<"Detach ..."<<Std::endl; Std::cout<<furesult.Get() <<Std::endl; return 0;}
3. Std::async provides methods for asynchronous execution, std::future = Std::async (...), which can be obtained by Std::future.get () to the return value of the execution function after the function execution is complete.
#include <iostream>#include<future>#include<chrono>intMainintargcConst Char*argv[]) {Std::future<int> Furesult =Std::async ([] () {std::this_thread::sleep_for (Std::chrono::seconds (Ten)); return 1; }); Std::cout<<"Detach ..."<<Std::endl; Std::cout<<furesult.Get() <<Std::endl; return 0;}
C++11の Async Method