DigestCPP

Lets Understand With Example

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

std::async with future 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::future

It is class, it provides access to outcome of task i.e return values or exception, get() API of future class is blocking call (it waits for the task to be finished) and return task outcome (return value or exception of task) if present. It invalidate the state so that second call of get() will give you a run time error.

source code and example:

/*
Program: async with future
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;
}

//Thread3
int ExcepThread(int a, int b)
{
    std::cout<<"Excep Thread"<<std::endl;
    //Genrating a exception
    int* p = new int[100000000000];
    std::cout<<"This line should not be printed"<<std::endl;
    return a+b;
}


int main()
{
    std::cout<<"Main thread to display the data"<<std::endl;

//Future return value cases
 
    //Using async to run the AddThread
    std::future<int>result1 = std::async(AddThread, 3, 3);

    //We can also use auto instead of future.
    auto result2 = std::async(MulThread, 3, 3);

    //get is blocking call, it will wait for function to be finished.
    std::cout<<"Add result:"<<result1.get()<<std::endl;
    std::cout<<"Mul Result:"<<result2.get()<<std::endl;

//Future return exception case
try
{
    //exception case
    std::future<int>result3 = std::async(ExcepThread, 3, 3);
    std::cout<<"Excep Result:"<<result3.get()<<std::endl;;
}
catch(const std::exception& e)
{
    std::cout<<"Got Exception:"<<e.what()<<std::endl;
}

    return 0;
}

Output:

Main thread to display the data
Mul ThreadAdd Thread
Add result:6
Mul Result:9
Excep Thread
Got Exception:std::bad_alloc

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer