DigestCPP

Lets Understand With Example

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

std::async with shared future c++11

std::async

It is an API provided by c++ standard library to execute the task (that is passes 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::shared future

It is class, it provides access to outcome of thread i.e return values or exception, get() API of shared::future class is blocking call (it waits for the thread to be finished) and return the outcome (return value or exception of thread) to multiple other waiting threads. It does not invalidate the state.

If multiple other threads are waiting to process the output of specific thread then we should use “std::shared_future” instead of  “std::future” because second call of get() API of std::future class will give run time error.

source code with example:

//Program: async with shared future
#include<iostream>
#include<future>

//InputThread
int InputThread(int a)
{
    std::cout<<"In Input Thread"<<std::endl;
    return (a*a);
}

//OutputThread1
int OutputThread1(int a, std::shared_future<int> f)
{
    std::cout<<"In Output Thread01"<<std::endl;
    return a*(f.get());
}

//OutputThread2
int OutputThread2(int a, std::shared_future<int> f)
{
    std::cout<<"In Output Thread02"<<std::endl;
    return a*(f.get());
}


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

    //Using async will be managed by library.
    //Using share_future because multiple other processes are waiting for this input.
    std::shared_future<int>result1 = std::async(InputThread, 3);

    //We can use either auto or future.
    //OutputThread1 and OutputThread2 is taking result1 as input
    auto result2 = std::async(OutputThread1, 3, result1);
    std::future<int>result3 = std::async(OutputThread2, 3, result1);

    //Main thread is being used to create other threads and display the result
    std::cout<<"OutputThread01 result:"<<result2.get()<<std::endl;
    std::cout<<"OutputThread02 Result:"<<result3.get()<<std::endl;

    return 0;
}

Output:

Main thread to display the data
In Input Thread
In Output Thread01
In Output Thread02
OutputThread01 result:27
OutputThread02 Result:27

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer