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:
- 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 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 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.
//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: