C11 Thread Management: asynchronous operations

Source: Internet
Author: User

1. Asynchronous operation

C++11 provides classes related to asynchronous operations, Std::future, std::p romise and std::p ackage_task. Std::future as the transmission channel of the asynchronous result, it is convenient to get the return value of the thread function; std::p romise is used to wrap a value, bind the data to the future, and facilitate thread assignment; STD::p ack_age is used to wrap a callable object, Bind the function to the future so that it can be called asynchronously.

1.1 Std::future

Threading in C11 makes it very convenient to create and use threads, but when we want to get the results of a thread function to be cumbersome, we can't get results directly from Thread.Join (), we need to define a variable, assign it inside the thread, and then execute the join to get the result.

So, the thread library provides a future to access the results of an asynchronous operation, because it is waiting for the thread to execute and get it in the next, so it becomes future,future provides a channel to get the results of the asynchronous operation, which can be synchronously waited to get the result of the operation. And you can query the status of the future to get the results of an asynchronous operation.

The State of the future:

Deferred, the asynchronous operation has not yet started;
Ready, the asynchronous operation has been completed;
Timeout, asynchronous operation timed out.

 //Query Statusstd::future_status status; Do{Status= Future.wait_for (Std::chrono::seconds (1)); if(Status = =std::future_status::d eferred) {        //Do sommething when deferred    }    Else if(Status = =Std::future_status::ready) {        //Do sommething if ready    }    Else    {        //Do sommething when timeout    } } while(Status! = Std::future_status::ready)

There are three ways to get the future: Get,wait,wait_for, where get waits for an asynchronous operation to end and returns a result, wait waits for the asynchronous operation to complete without a return value; Wait_for is a timeout to wait for the result to return.

1.2 std::p romise

std::p romise can assist thread assignment, bind the data to the future, facilitate the acquisition of a value in a thread, promise assignment outside the thread function, and then obtain the value by promise the bound future after the threading function has finished executing. The value is obtained indirectly through the future provided internally by the promise.

     std::p romise<int> PR;    Std::thread T ([] (std::p romise<int> & P) {p.set_value_at_thread_exit (9);}, std:: ref (PR));    Std::future<int> f = pr.get_future ();     int i = f.get();     // after execution i = 9
1.3 std::p ackage_task

std::p Ackage_task Wraps a wrapper class for a callable object (such as Function,lambda expression,bind expression, and other function objects), binds the function to the future so that it can be called asynchronously. The difference between it and promise is that promise binds a variable, and package_task is a function of the binding.

    std::p ackaged_task<intreturn5;});    Std::thread T1 (std::ref(Task));    Std::future<int> f1 = task.get_future ();     int i = F1. Get ();     // after execution i = 5
1.4 Three-person relationship

The future provides a mechanism to access the results of a thread's asynchronous operation, and the thread is a level, belonging to the bottom. Package_task and promise are internally future,promise is the packaging of a value, and Package_task is the packaging of an Operation object, the specific use of which should be based on the actual situation to make a distinction.

It should be noted that the future is non-copy, can only be moved, Shared_future can be copied, if necessary to put in containers or other places, you need to use the shared_future.

2. Thread Asynchronous Operation Std::async

Std::async std::p romise, std::p ackage_task and Std::thread, it can be used to create asynchronous tasks directly, the results of the asynchronous task is saved in the future, when you need to get the results of thread execution, can be obtained through future.get (), if you do not pay attention to the results of the asynchronous task, but simply wait for the task to complete, then call Future.wait ().

Std::async is a higher level of asynchronous operations, which makes it easy to get the results of thread asynchronous execution without worrying about the internal details of thread creation, but also to specify thread creation policies and, more often, to use Std::async to create threads and become the first choice for asynchronous operations.

The Std::async prototype is Std::async (Std::launch::async | std::launch::d eferred,f,args ...), the first parameter is the thread's creation policy, the second is the thread function, and the other is the parameter of the thread function.

There are two ways to create a policy:

Std::launch::async: Start creating threads when Async is called;
Std::launch::d eferred: Lazy loading creates a thread, calling async without creating a thread until the future's get or wait method is called to create the thread.

#include <thread>#include<iostream>#include<mutex>#include<future>intMain () {std::future<int> f1 = Std::async (Std::launch::async, [] () {return 8; }); Std::cout<< F1.Get() << Std::endl;//Output 8std::future<void> F2 = Std::async (Std::launch::async, [] () {std::cout <<8<<Std::endl;}); F2.wait (); //Output 8std::future<int> F3 =Std::async (Std::launch::async, [] () {std::this_thread::sleep_for (Std::chrono::seconds (3)); return 8;    }); Std::cout<<"wating ..."<<Std::endl;    Std::future_status status;  Do{Status= F3.wait_for (Std::chrono::seconds (1)); if(Status = =std::future_status::d eferred) {Std::cout<<"deferred."<<Std::endl; }        Else if(Status = =std::future_status::timeout) {Std::cout<<"timeout."<<Std::endl; }        Else{std::cout<<"Ready ."<<Std::endl; }    }  while(Status! =Std::future_status::ready); Std::cout<<"Result:"<< F3.Get() <<Std::endl; return 0;}//Execution Result:88Wating...timeout.timeout.ready.result:8

C11 Thread Management: asynchronous operations

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.