c++11 Multithreading--<future> std::p romise Learning

Source: Internet
Author: User

Introduction to a <future> header file
1 Classes

Std::future

Std::future_error

std::p ackaged_task

std::p romise

Std::shared_future

2 Functions

Std::async

Std::future_category

Two std::p romise class
1 std::p romise class statement
Template <class t> Promise; Template <classR&> promise<r&>//Specialization:t is a reference type (r&) template <> Prom Ise<void>;//specialization:t is void

2 Introduce std::p romise

The Promise object can hold a value of type T, which can be read by the future object (possibly in another thread), which is a means of synchronization provided by the promise. When constructing promise, the promise object can be associated with a shared state, which can store a value of type T or a class derived from std::exception, and can be get_future to get the object associated with the Promise object. After the function is called, two objects share the same shared state

The Promise object is an asynchronous provider that can set the value of a shared state at some point

The future object can return a shared state value, or, if necessary, block the caller and wait for the shared status identity to become ready before the shared status can be obtained.

There is a simple example to explain above relations:

#include <iostream>//std::cout#include <future>//std::p romisestd::future#include <thread>//std: : Thread#include <functional>//std::ref void Printint (std::future<int>&fut) {        int x = Fut.get ();        Std::cout << "value =" << x << "\ n";} int main (int argc, _tchar* argv[]) {        std::p romise<int> prom;        Std::future<int>fut =prom.get_future ();//Associate prom with fut        std::thread th (printint,std::ref (fut));//New Thread, Execute the Printint function         prom.set_value (10);//Set the shared state value        th.join ();        return 0;}

3 std::p Romise Constructor

Default (1)                  promise () with allocator (2)           template<class alloc>promise (allocator_arg_t,aa,const Alloc &ALLOC); Copy[delete] (3)             Promise (constpromise&) = delete; Move (4)                     Promise (Constpromise&&x) noexcept;

(1) Default constructor

Initializing an empty shared state

(2) Constructor with allocator

Similar to the default constructor, but uses a custom allocator to assign shared state

(3) Copy constructor [Delete] (4) Move constructor
There is aexample to explain the std::p romise Constructor:

//promise constructors#include <iostream>//std::cout# Include <functional>//Std::ref#include <memory>//Std::allocator,std::allocator_arg#include < ;thread>//Std::thread#include <future>//std::p romise, std::future void Print_int (std::future&        lt;int>& fut) {int x = Fut.get (); Std::cout << "Value:" << x << ' \ n ';}        int main () {std::p romise<int> foo;         std::p romise<int> bar = std::p romise<int> (std::allocator_arg,std::allocator<int> ());         Std::future<int> fut =bar.get_future ();         Std::thread th (Print_int,std::ref (fut));         Bar.set_value (20);        Th.join ();
  return 0;} 


4 std::p romise member functions
4.1std::p romise::get_future

The change function returns a future object associated with the promise shared state. The returned future object can access the value set by the Promise object in the shared state or an exception object. And can only get a future object from the shared state of the Promise object. After the function is called, the Promise object is usually set at a point in time (a value or an exception object), and if no value or exception is set, Promise automatically sets a Future_error exception to set its own readiness state when it is refactored.

4.2 std::p romise::set_value

GenericTemplate            void Set_value (constt& val)                           void Set_value (t&& val) specializations            void Promise<r&>::set_value (r&val)                           void Promise<void>::set_value (void)

Set the shared state value, after which the promise shared status identity becomes ready

4.3std::p romise::set_exception

Set an exception for promise, after which the shared status identity of promise becomes ready

Example:

Promise::set_exception#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_exception void Get_int (std::p romise<int>& Prom) {        int x;        Std::cout << "Please, Enteran integer value:";   Std::cin.exceptions (Std::ios::failbit);                           Throw on Failbit try {std::cin >> x;        Sets Failbit ifinput is not int prom.set_value (x);        } catch (std::exception&) {prom.set_exception (std::current_exception ());                  }} void Print_int (std::future<int>& fut) {try {int x = Fut.get ();        Std::cout << "Value:" << x << ' \ n ';           } catch (std::exception& e) {       Std::cout << "[exceptioncaught:" << e.what () << "]\n";        }} int main () {std::p romise<int> prom;         Std::future<int> fut =prom.get_future ();        Std::thread Th1 (Print_int,std::ref (fut));         Std::thread Th2 (Get_int,std::ref (prom));        Th1.join ();        Th2.join (); return 0;}


4.4 std::p romise::set_value_at_thread_exit

Set the shared state value, but not set it immediately, promise automatically set the shared state value when the thread exits. If a future object is associated with a promise object and the future object is calling get, the thread that called get is blocked, and when the thread exits, the thread that calls Future::get automatically unblocked and returns Promise::set_value_ The value set by the At_thread_exit

Note: the thread to set the value of promise, if there are other modifications to the shared state after the end of a thread is worth the action, the Future_error (promise_already_satisfied) exception is thrown

          4.5 std::p romise::operator = (move Assignment)

//promise::operator= #include <iostream>//Std::cout#in Clude <thread>//std::thread#include <future>/std::p romise, std::future std::p romise<in t> prom;        Voidprint_global_promise () {std::future<int> fut =prom.get_future ();        int x = Fut.get (); Std::cout << "Value:" << x << ' \ n ';}        int main () {std::threadth1 (print_global_promise);        Prom.set_value (10);         Th1.join ();    Prom = std::p romise<int> ();        Reset, by move-assigning a new Promise std::threadth2 (print_global_promise);        Prom.set_value (20);         Th2.join ();
  return 0;} 


4.6 std::p romise::swap (non-member-overloads)

Exchange two promise sharing status

c++11 Multithreading--<future> std::p romise Learning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.