std::packaged_task
It is class template, it executes the task (that is passed as argument) as asynchronously (create separate thread) always and process the outcome of background task using future object. We can start the task (thread) on specific condition or specific time (It means object creation of class (std::packaged_task) will NOT start the thread, we need to trigger a separate call to start the thread).
What is the difference between async and packaged_task (std::sync vs packaged_task) ?
std::packaged_task:
- Execute the task as asynchronously (create separate thread) always.
- Process the outcome of task using future object.
- Object creation of std::packaged_task will NOT start the thread (Unlike class thread), we need to trigger a separate call to start the thread.
- Move operation can be done on task.
std::async:
- We have both options, we can execute either asynchronously (create separate thread) or synchronously (normal call to function)
- Also process the outcome of task using future object.
- Thread will be started as we trigger the call to async with std::launch::async.
- Cannot move the task
Source code with example:
/* Program: Packaged Task Author: Alpha Master Date:31 Jan 2021 */ //Header File #include<iostream> #include<future> #include<thread> //Thread1 int AddThread(int a, int b) { std::cout<<"Start Thread"<<std::endl; auto i{0}; while(i<5) { std::cout<<"Waiting..."<<std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); ++i; } return a+b; } int main() { std::cout<<"Main thread"<<std::endl; //Create task. std::packaged_task<int(int, int)> task(AddThread); //Create future object, get the shared state that has //been created by packaged_task std::future<int>result1 = task.get_future(); //start the task, as separate thread; task(5,5); //get is blocking call std::cout<<"Before get()"<<std::endl; std::cout<<"Add result:"<<result1.get()<<std::endl; return 0; }
Output:
Main thread Start Thread Waiting... Waiting... Waiting... Waiting... Waiting... Before get() Add result:10