C++11の Async Method

Source: Internet
Author: User

1. std::p romise can be used to provide data transfer between threads.

std::future = std::p romise.get_future ().

Promise can be assigned to a thread in std::p romise.set_value.

After the assignment, Std::future.get () returns the value set in the other thread.

#include<iostream>#include<future>#include<chrono>std::p romise<int>promis;intMainintargcConst Char*argv[]) {Std::future<int> Furesult =promis.get_future (); Std::thread T ([] () {std::this_thread::sleep_for (Std::chrono::seconds (Ten)); Promis.set_value (123);    });    T.detach (); Std::cout<<"Detach ..."<<Std::endl; Std::cout<<furesult.Get() <<Std::endl; return 0;} 

2. std::packaged_task can wrap a function, somewhat similar to std::function, except that this can get the result of a function executed asynchronously by Get_future returning the Std::future object.

#include <iostream>#include<future>#include<chrono>intMainintargcConst Char*argv[]) {std::p ackaged_task<int() >m ([] () {std::this_thread::sleep_for (Std::chrono::seconds (Ten)); return 123;    }); Std::future<int> Furesult =m.get_future ();    Std::thread Task (Std::move (m));    Task.detach (); Std::cout<<"Detach ..."<<Std::endl; Std::cout<<furesult.Get() <<Std::endl; return 0;}

3. Std::async provides methods for asynchronous execution, std::future = Std::async (...), which can be obtained by Std::future.get () to the return value of the execution function after the function execution is complete.

#include <iostream>#include<future>#include<chrono>intMainintargcConst Char*argv[]) {Std::future<int> Furesult =Std::async ([] () {std::this_thread::sleep_for (Std::chrono::seconds (Ten)); return 1;    }); Std::cout<<"Detach ..."<<Std::endl; Std::cout<<furesult.Get() <<Std::endl; return 0;}

C++11の Async Method

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.