std::thread
It 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:
- Joinable (Main thread will wait for it using API join(T1.join())
- 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 (parent) thread from newly created thread?
Solution : Promise object(store the value) and Future object(fetch the value)
- Create Promise object and pass it as argument during thread creation
- Create Future object and pass above Promise object as argument.
- During thread execution, fill the promise object using set_value().
- After filling the value in promise, future object will get the value in shared memory.
- Future object will wait the value using get(), its blocking call.
Actual Purpose
We want to return the value of exception to calling thread BUT there is another condition we want thread to continue (this is the catch), if only want return value or exception at the end of thread then we can directly use future object to collect the return (see std::async with future)
//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(100)*a); //store the value in promise object p.set_value(a*2); std::cout<<"I have filled the promise but this thread still can continue"<<std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout<<"Puspose of promise is to returned the value BUT want thread to continue"<<std::endl; std::cout<<"This statement should be executed at the end"<<std::endl; 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; t1.join(); return 0; };
Output:
Thread with promise and future Inside ThreadFunction:5 I have filled the promise but this thread still can continue Result:10 Purpose of promise is to returned the value BUT want thread to be continue This statement should be executed at the end