The promise internally creates a shared state that is used to put a corresponding type of value or an exception, and can be taken by the future object as the thread results
Promise the results into a shared state after the result is formed. So there is no concurrent operation to read and write
#include <thread>#include<future>#include<iostream>#include<string>#include<exception>#include<random>//random Number class#include <chrono>//Time Processing Class#include <stdexcept>//Standard Exception class#include <functional>//STL-defined arithmetic functions (substitution operators)#include <utility>//STL Generic template classusing namespacestd;voidTosomething (promise<string> &p) { Try{cout<<"Read char (' x ' for exception):"; //char C = cin.get (); CharC; Default_random_engine Dre (Time (NULL)); Uniform_int_distribution<int> ID (0, -); C='a'+ID (DRE); //this_thread::sleep_for (Chrono::milliseconds ()); if(c = ='x') { ThrowRuntime_error (string("Char") +"Read"); } strings =string("Char") + C +"processed"; //When the main function calls the Get () method, the thread will stall (block) until share state becomes ready-when Promise's Set_value () or set_exception () is executed. Nor does it mean that the promise thread has ended;//the thread may still be executing other statements, or even storing other results in other promise. //You should use Set_value_at_thread_exit () and set_ if you want the shared state to be ready-to make sure that the thread's local object and other materials are cleared before releasing the thread when it really ends. Exception_at_thread_exit () to prevent leakageP.set_value_at_thread_exit (Move (s)); } Catch(ConstException &e) {p.set_exception_at_thread_exit (current_exception ()); }}intMain () {Try{Promise<string>p;//defines a Promise object before the thread definition. The promise internally creates a shared state of Y, where//is used to put a corresponding type of value or an exception, and can be taken by the future object its data when the thread results//The promise is then passed to a task that runs in a separate thread:Thread T (tosomething,ref(p));//by ref (), ensure that promise is passed by reference (address) so that it can be changed. T.detach ();//detach threads from the main thread so that they run in the backgroundfuture<string> f (p.get_future ());//defines a future () that is used to fetch promise results, which matches the promise ()cout <<"Result:"<< F.Get() << Endl;//Gets the result of the thread } Catch(ConstException &e) {Cerr<<"EXCEPTION:"<< e.what () <<Endl; } System ("Pause"); return 0;}
c++promise function