HTTP://WWW.CNBLOGS.COM/HAIPPY/P/3279565.HTMLSTD: Introduction to the class of the:p romise
The Promise object can hold the value of a type T, which can be read by the future object (possibly in another thread), so promise also provides a means of thread synchronization. Promise object constructs can be associated with a shared state (typically Std::future) and a value of type T can be saved on the associated shared state (std::future).
You can get the future object associated with the Promise object by Get_future, and after calling the function, two objects share the same shared state
- The Promise object is an asynchronous Provider that can set the value of a shared state at a certain point in time.
- The future object can return the value of the shared state asynchronously or, if necessary, block the caller and wait for the shared status flag to become ready before the shared status can be obtained.
#include <iostream>//Std::cout#include <functional>//Std::ref#include <thread>//Std::thread#include <future>//std::p romise, Std::futurevoidPrint_int (std::future<int>&fut) { intx = Fut.Get();//gets the value of the shared state.Std::cout <<"Value:"<< x <<'\ n';//print value:10.}intMain () {std::p romise<int> Prom;//generates an std::p romise<int> object.std::future<int> fut = prom.get_future ();//associated with the future.Std::thread T (print_int, std::ref(fut));//give the future to another thread T.Prom.set_value (Ten);//sets the value of the shared state, where it is synchronized with the thread T.T.join (); return 0;}
#include <iostream>//std::cin, Std::cout, Std::ios#include <functional>//Std::ref#include <thread>//Std::thread#include <future>//std::p romise, Std::future#include <exception>//std::exception, Std::current_exceptionvoidGet_int (std::p romise<int>&prom) { intx; Std::cout<<"Please , enter an integer value:"; Std::cin.exceptions (Std::ios::failbit); //throw on Failbit Try{std::cin>> x;//sets Failbit If input is not intprom.set_value (x); } Catch(std::exception&) {prom.set_exception (std::current_exception ()); }}voidPrint_int (std::future<int>&fut) { Try { intx = Fut.Get(); Std::cout<<"Value:"<< x <<'\ n'; } Catch(std::exception&e) {std::cout<<"[Exception Caught:"<< e.what () <<"]\n"; }}intMain () {std::p romise<int>prom; Std::future<int> fut =prom.get_future (); Std::thread Th1 (Get_int, std::ref(prom)); Std::thread Th2 (Print_int, std::ref(fut)); Th1.join (); Th2.join (); return 0;}
Thread--promise furture Synchronization