C ++ 11 std: future and std: promise, stdfuture

Source: Internet
Author: User

C ++ 11 std: future and std: promise, stdfuture

Why does C ++ 11 introduce std: future and std: promise? After a thread is created in C ++ 11, we cannot directly. join () is returned. A variable must be defined. During thread execution, the variable is assigned a value and then join () is executed. This process is relatively cumbersome.

  The thread Library provides the future for accessing the asynchronous operation results. Std: promise is used to wrap a value and bind the data to the future. It facilitates obtaining a value in the thread function. The value is obtained indirectly through the future provided by promise, that is to say, the promise level is higher than that of future.

# Include "stdafx. h "# include <iostream> # include <type_traits> # include <future> # include <thread> using namespace std; int main () {std: promise <int> promiseParam; std: thread t ([] (std: promise <int> & p) {std: this_thread: sleep_for (std: chrono: seconds (10 )); // thread sleep for 10 s p. set_value_at_thread_exit (4); //}, std: ref (promiseParam); std: future <int> futureParam = promiseParam. get_future (); auto r = futureParam. get (); // out-of-thread blocking waits for std: cout <r <std: endl; return 0 ;}

The above program is executed to futureParam. get () has two threads, the new thread is sleeping for 10 s, and the main thread is waiting for the exit value of the new thread, this operation is blocked, that is, std :: future and std: promise can also be used as thread synchronization to some extent.

Std: packaged_task wraps a callable object packaging class (such as a function or lambda expression (C ++ 11 lambda expression) and binds the function to the future. Std: packaged_task and std: promise both have the get_future () interface. However, std: packaged_task encapsulates an asynchronous operation, while std: promise encapsulates a value.

# Include "stdafx. h "# include <iostream> # include <type_traits> # include <future> # include <thread> using namespace std; int main () {std: packaged_task <int ()> task ([] () {std: this_thread: sleep_for (std: chrono: seconds (10); // The thread sleeps for 10 s return 4 ;}); std: thread t1 (std: ref (task); std: future <int> f1 = task. get_future (); auto r = f1.get (); // outside-thread blocking waits for std: cout <r <std: endl; return 0 ;}

Std: async is higher than std: promise, std: packaged_task and std: thread. It can be used directly to create asynchronous tasks, the results returned by the asynchronous task are also saved in future. Std: async prototype:

async( std::launch policy, Function&& f, Args&&... args );

There are two std: launch policies. One is the call to create a thread (std: launch: async), and the other is the delay loading method to create a thread (std: launch :: deferred). When async is used, no threads are created and the future get or wait is called. Followed by thread functions and thread parameters.

#include "stdafx.h"#include <iostream>#include <future>#include <thread>int main(){    // future from a packaged_task    std::packaged_task<int()> task([]() {         std::cout << "packaged_task started" << std::endl;        return 7; }); // wrap the function    std::future<int> f1 = task.get_future();  // get a future    std::thread(std::move(task)).detach(); // launch on a thread                                           // future from an async()    std::future<int> f2 = std::async(std::launch::deferred, []() {         std::cout << "Async task started" << std::endl;        return 8; });    // future from a promise    std::promise<int> p;    std::future<int> f3 = p.get_future();    std::thread([&p] { p.set_value_at_thread_exit(9); }).detach();    f1.wait();    f2.wait();    f3.wait();    std::cout << "Done!\nResults are: "        << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';}

 

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.