C + + Async

Source: Internet
Author: User

Consider the following code:

#include <iostream>#include<string>#include<thread>#include<mutex>#include<condition_variable>Std::mutex m;std::condition_variable cv;std::stringdata;BOOLReady =false;intresult =0; voiddo_work () {std::this_thread::sleep_for (Std::chrono::seconds (1)); Result=123; {Std::lock_guard<std::mutex>LK (m); Ready=true; } cv.notify_one ();} intMain () {Std::thread thread (do_work);        Thread.detach (); Std::unique_lock<std::mutex>LK (m); Cv.wait (LK, []{returnReady ;}); Std::cout<<"result="<< result <<'\ n';}

C++11 introduces promise and future, and can use task-based thinking

#include <iostream>#include<cstdlib>#include<future>#include<chrono>voidDo_work (std::p romise<int>promise) {std::this_thread::sleep_for (Std::chrono::seconds (1)); Promise.set_value (123);}intMain () {std::p romise<int>promise; Std::future<int> Future =promise.get_future ();    Std::thread thread (do_work, Std::move (Promise));    Thread.detach ();    Future.wait (); Std::cout<<"result="<< future.Get() <<'\ n';}

See, is it a lot of code streamlining? Now continue streamlining, using the Std::async code as follows:

#include <iostream>#include<cstdlib>#include<future>#include<chrono>intMain () {std::future<int> Future =Std::async ([] () {std::this_thread::sleep_for (Std::chrono::seconds (1)); return 123; });    Future.wait (); Std::cout<<"result is"<< future.Get() <<'\ n';}

In addition, introduce a C + + online compiler https://wandbox.org/

C + + Async

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.