DigestCPP

Lets Understand With Example

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

std::thread with promise c++11

std::thread is class in c++11, we can create a thread and start it just declaring an object of this class like any other object in c++. Example:

std::thread T1 (threadfunction, other argument if required)

There are two type of thread:

  1. Joinable (Main thread will wait for it using API join(T1.join())
  2. Detachable (Main thread will not wait for it, make it detachable using API T1.detach())

Now question is How we will pass the value or exception to calling thread ?

Solution : Promise object(store the value) and Future object(fetch the value)

  1. Create Promise object and pass it as argument during thread creation
  2. Create Future object and pass Promise object as argument.
  3. During thread execution, fill the promise object using set_value().
  4. After filling the value in promise, future object will get the value in shared memory.
  5. Future object will wait the value using get(), its blocking call.
//Program to explain the std thread with promise and future

#include<iostream>
#include<thread>
#include<future>

void ThreadFunction(int a, std::promise<int>& p)
{
    std::cout<<"Inside ThreadFunction:"<<a<<std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(1000)*a);
    //store the value in promise object
    p.set_value(a*2);
    return ;
}


int main()
{
    std::cout<<"Thread with promise and future"<<std::endl;

    //Create Promise object that will be used to store value in thread
    std::promise<int> p;

    //Thread 1  and its detachable, main thread will NOT wait for it.
    std::thread t1(ThreadFunction, 5, std::ref(p));
    t1.detach();

    //Create Future Object that will be used to retrieve value
    //same value has been stored using promise object so we need
    //to pass promise object as argument to future object
    std::future<int> f=p.get_future();

    //get the value using get(), This is BLOCKING Call
    int result = f.get();
    std::cout<<"Result:"<<result<<std::endl;

    return 0;
};

Output:

 

Primary Sidebar

DigestCPP © 2022. All rights reserved from 2019.

    Contact Us   Disclaimer