Example
Asssume you have one or more time consuming calculations finally providing some result:
class CalculateSomething1
{
public:
CalculateSomething(int in_val);
SomeResult1 operator()() {return ...}
};
class CalculateSomething2
{
...
};
Then you can store the execution within a task:
#include <future>
{
CalculateSomething1 calc1(17);
CalculateSomething2 calc2(42);
std::packaged_task<SomeResult1()> calcTask1(calc1);
std::packaged_task<SomeResult2()> calcTask2(calc2);
std::future<SomeResult1> calcResult1 = calcTask1.get_future();
std::future<SomeResult2> calcResult2 = calcTask2.get_future();
std::thread thread1 (std::move(calcTask1));
thread1.detach();
std::thread thread2 (std::move(calcTask2));
thread2.detach();
SomeResult1 result1 = calcResult1.get();
SomeResult2 result2 = calcResult2.get();
}
Remarks
Several packaged_tasks may be stored within a container and client code can use a set of available worker threads to process all container entries.
std::packaged_task - most used features
Method | Description |
get_future | returns the future for later accessing the promised result |
operator() | executes the function which is stored within the packaged task. The function is executed in the calling thread! The client code is responsible for using a separate thread. |
For more info see std::packaged_task - complete reference at CppReference.com