std::async
It is an API provided by c++ standard library to execute the task (that is passed as argument) either asynchronously (create separate thread) or synchronously (normal call to function). It depends upon launch policy (please check this std::async with std::launch).
std::future
It is class, it provides access to outcome of task i.e return values or exception.
There are four member functions of Future Class, which are used to interact with std::async function.
- get() :
- It is blocking call ( it waits for the function to be finished)
- return the result (return value or exception of function) if present.
- It invalidates the state so that second call of get() will give run time error.
- if deferred policy then get() will also trigger the function call
- wait() :
- It is blocking call ( it waits for the function to be finished)
- It don’t touch the state so that we can call wait() multiple time.
- if deferred policy then wait() will also trigger the function call
- wait_for(duration) :
- It is blocking call for specific duration(given duration)
- It don’t touch the state so that we can call wait_for() multiple time.
- if deferred policy then this will NOT trigger the function call
- wait_until(time point):
- It is blocking call till given time point
- It don’t touch the state so that we can call wait_untill() multiple time.
- if deferred policy then this will NOT trigger the function call
source code and example:
/* Program: async with wait Author: Alpha Master Date:30 Jan 2021 */ //Header File #include<iostream> #include<future> #include<exception> //Thread1 int AddThread(int a, int b) { std::cout<<"Add Thread"<<std::endl; return a+b; } //Thread2 int MulThread(int a, int b) { std::cout<<"Mul Thread"<<std::endl; return a*b; } int main() { std::cout<<"Main thread to display the data"<<std::endl; //Using async to run the AddThread std::future<int>result1 = std::async(AddThread, 3, 3); //wait is blocking call, it will ONLY wait for function to be finished. //if deferref policy then wait will also trigger the function call. result1.wait(); //we can call wait more than one time, second call of get() will //give run time error. result1.wait(); //get is blocking call + get the result or exception std::cout<<"Add result:"<<result1.get()<<std::endl; //We can also use auto instead of future. //call asyn with async policy auto result2 = std::async(std::launch::async, MulThread, 3, 3); //wait_for zero, mean continously polling if(result2.wait_for(std::chrono::seconds(0)) != std::future_status::deferred) { while(result2.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { std::cout<<"Waiting"<<std::endl; } std::cout<<"Ready"<<std::endl; } std::cout<<"Mul Result:"<<result2.get()<<std::endl; return 0; }
Output:
Main thread to display the data Add Thread Add result:6 Waiting Waiting Mul Thread Ready Mul Result:9