New features in C ++ 11: std: ure and std: async

Source: Internet
Author: User

New features in C ++ 11: std: ure and std: async

Let's start with an episode. Baidu Translation:

Std: future

Imagine that you want a thread to do something and then return you a result. At the same time, if you are doing some other work, it may not take you some time. You want to get the results of that thread at a specific time.
In win32, you can
Use CreateThread to start a thread
In the thread, start the task, send an event after preparation, and put the result in the global variable.
Do other things in the main function, and then call WaitFZ compile where you want the result? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> labels/vrnKx8qyw7TE2KO/labels/J0tTTw8C0u/labels + 8wsfSu7j2vPK1pbXEysK2 + labels =" brush: java; ">std::thread t([]() { auto res = perform_long_computation(); });

Std: thread has been introduced in previous blogs. Can we make it more efficient?

MyResult sharedRes;std::thread t([&]() { sharedRes = perform_long_computation(); });

At this time, we should know when the thread will be executed. Here is a very simple method.

auto result = std::async([]() { return perform_long_computation(); });MyResult finalResult = result.get();

The appeal code is concise and clear. We need to understand its principles.
The English description may be more accurate:
Std: future holds a shared state
Std: async allow us to run the code asynchronously.
Therefore, the following code is available:

std::future
  
    result = std::async([]() { return perform_long_computation(); });MyResult finalResult = result.get();
  

The previous complete code:

// future example#include 
  
    // std::cout#include 
   
     // std::async, std::future#include 
    
      // std::chrono::milliseconds// a non-optimized way of checking for prime numbers:bool is_prime (int x) {for (int i=2; i
     
       fut = std::async (is_prime,444444443);   // do something while waiting for function to set future:  std::cout << checking, please wait;  std::chrono::milliseconds span (100);  while (fut.wait_for(span)==std::future_status::timeout)    std::cout << '.' << std::flush;  bool x = fut.get();     // retrieve return value  std::cout << 444444443  << (x?is:is not) <<  prime.;  return 0;}
     
    
   
  

Output:
Checking, please wait ........................
444444443 is prime.

Std: async
Why use std: async to replace thread creation?

Std: async is designed to make users less cost-efficient, which makes the three objects work together. The general working process is as follows: std: async first wraps the asynchronous operation with std: packaged_task, and then stores the result of the asynchronous operation in std: promise, this process is the process of creating the future. You can use future outside. how about get/wait to get the future results? std: async is really helpful. You don't have to think about how to use std: future, std :: promise and std: packaged_task. std: async has done everything for you!

Now let's take a look at the prototype of std: async.

async(std::launch::async | std::launch::deferred, f, args...)

The first parameter is the thread creation policy. There are two policies. The default policy is to create a thread immediately:
Std: launch: async: The thread is created when async is called.
Std: launch: deferred: Creates a thread in the delayed loading mode. No thread is created when async is called, and the thread is not created until the future get or wait is called.
The second parameter is the thread function, and the third parameter is the parameter of the thread function.

std::future
  
    future = std::async(std::launch::async, [](){     std::this_thread::sleep_for(std::chrono::seconds(3));    return 8;  }); std::cout << waiting...;std::future_status status;do {    status = future.wait_for(std::chrono::seconds(1));    if (status == std::future_status::deferred) {        std::cout << deferred;    } else if (status == std::future_status::timeout) {        std::cout << timeout;    } else if (status == std::future_status::ready) {        std::cout << ready!;    }} while (status != std::future_status::ready); std::cout << result is  << future.get() << '';
  

Possible results:
Waiting...
Timeout
Timeout
Ready!
Result is 8

Write code snippets here
''

 

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.