Updated April 15, 2023
Introduction to C++ async-await
Async/await in the computer programs is a syntactic feature of numerous programming languages that permits an asynchronous as well as the non-blocking method to be arranged in a way like a normal synchronous method. Async and await helps in writing asynchronous code simply. For example, performing some calculations while getting some information from I/O. Asynchronous code increases the responsiveness and is explained as a close way to write applications on multithreading applications. In this topic, we are going to learn about C++ async-await.
Syntax
Below is the syntax of async.
std::async()
Parameters are:
1. Policy: It is a bitmask value that indicates the launching policy.
- launch::async- This is asynchronous, and it launches a new thread to call the function as if the object of the thread is created with functions and arguments and access the state shared from the returned future.
- launch::deferred- This is deferred, and the call to the function is deferred till the returned future’s shared state is accessed with get or wait. In that instance, the function is called, and it is no longer thought of as deferred. At the time when this particular call is returned, the returned future’s shared state gets ready.
- launch::async|launch::deferred- This is automatic, and the function selects the policy automatically at a particular point. This is dependent on the system as well as library implementation, which usually optimizes for the present concurrency availability in the system
2. fn: It is a pointer to the function, member, or any type of move-constructible function object whose class defines the operator() that consists of closures as well as functional objects. Here, the function makes use of the decay copy of the parameter. The fn return value is saved as the shared state to attain be the future object that is returned by async. In case the fn throws, it will set an exception in the shared state that is to be attained by the future object.
3. Args: These are the arguments that are passed to the function call if available. Here also, the type will be move-constructible. If fn is considered a member pointer, the argument one will be an object where the member is defined or a pointer or a reference. Moreover, the function makes use of the decay copies of the arguments as well.
In this, the fn and args are considered as the template parameters. That is, if it is implicitly deduced, these will be the argument’s appropriate lvalue/rvalue reference types.
The return value is:
Here, the return value will be a future object with a shared state getting ready when the fn execution ends. The value attained by the future:: get member will be the value that is returned by function fn (if any). In the case where launch::async is chosen, the future returned is connected to the created thread’s end, even though the shared state has never been accessed. In this situation, the return of fn synchronizes with fn return. As a result, the return value will not be ignored for its asynchronous behavior at the time when the function fn returns void.
Fn returns the type result_of::type when it is called with parameters of the types in Args.
Examples of C++ async await
Given below are the example of C++ async await:
Example #1
Code:
// c++ program that demonstrates async
// library for std::cout
#include <iostream>
//library for std::async and std::future
#include <future>
// check whether it is prime number or not
//parameter is the number that has to be checked
bool fnprime (int num)
{
std::cout << "Process started. . . Just wait. . . \n";
//loop starts here
for ( int i = 2 ; i<num ; ++i )
//if the mod is 0, return false, else return zero
if (num%i==0)
{
return false ;
}
return true ;
}
//main method
int main ()
{
// call the function fnprime() asynchronously to check whether the number is prime or not:
std::future<bool> fobj = std::async (fnprime,4);
//print the line to show the status
std::cout << "check whether the number 4 is prime or not . . \n";
//waits for the the function fnprime to return
bool bobj = fobj.get();
//prints the result
if (bobj) std::cout << "The number given is prime . . . ! \n";
else std::cout << "The number given is not prime . . . ! \n\n";
return 0;
}
Output:
Example #2
In this example, a number is given to check whether it is prime or not. For that, a function fnprime() is available, and it will be called asynchronously. Here the number to be checked is given as 4. On executing the code, the result will be printed as shown above.
Suppose the number given is 3, as mentioned below. Then the result will be prime as 3 is a prime number.
std::future<bool> fobj = std::async (fnprime,3);
.
Code:
// c++ program that demonstrates async
// library for std::cout
#include <iostream>
//library for std::async and std::future
#include <future>
//library for std::string
#include <string>
std::string samplefunction(const std::string& st)
{
return "This is the output of " + st ;
}
class SamplefunctionObject
{
public:
std::string operator()( const std::string& st) const
{
return "This is the output of " + st ;
}
};
int main()
{
std::cout << std::endl;
// future with the help of function
auto ff = std::async(samplefunction,"sample function");
// future with the help of function object
SamplefunctionObject samplefunctionObject;
auto ffo= std::async(samplefunctionObject,"sample function object");
// future with the help of lambda function
auto fl= std::async([]( const std::string& st )
{
return "This is the output of " + st ;} , " lambda function" );
std::cout << ff.get() << "\n"
<< ffo.get() << "\n"
<< fl.get() << std::endl;
std::cout << std::endl;
}
Output:
In this program, all the necessary libraries are imported first. Then, on executing the code, messages get displayed with the help of function, function object, and lambda function.
Conclusion
Async and await in C++ helps in writing asynchronous code simply. Calculation and getting data from I/O is an example for Async/await operations. In this article, different aspects such as syntax and examples are explained in detail.
Recommended Articles
This is a guide to C++ async await. Here we discuss the different aspects such as syntax and examples of C++ async await explained in detail. You may also have a look at the following articles to learn more –