DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

std::async with lambdas c++11

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::async run the background task, we can pass the required arguments either directly or using lambdas.

//Using Lambdas
auto result2 = std::async(std::launch::deferred,[]()->int {MulThread(3,3);});
//Without lambdas, directly passing function name and its argument
auto result2 = std::async(std::launch::deferred, MulThread, 3, 3);

std::future

It is class, it provides access to outcome of thread i.e return values or exception. For more detail on async and future please check this std::async with future.

source code and example:

/*
Program: async with Lambdas
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 std::launch::async policy, create separate thread
    std::future<int>result1 = std::async(std::launch::async,[]()->int{AddThread(3,3);});

    //Using std::launch::deferred policy, no separate thread(synchronous call).
    //MulThread will be called when get() is called.
    auto result2 = std::async(std::launch::deferred, []()->int { MulThread(3, 3);});

    //get is blocking call
    std::cout<<"Add result:"<<result1.get()<<std::endl;
    std::cout<<"Mul Result:"<<result2.get()<<std::endl;

    return 0;
}

Output:

Main thread to display the data
Add Thread
Add result:6
Mul Thread
Mul Result:9

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer