...

/

Introduction to std::packaged_task

Introduction to std::packaged_task

This lesson gives an introduction to std::packaged_task which is used in C++ for multithreading.

We'll cover the following...

std::packaged_task pack is a wrapper for a callable, which allows it to be invoked asynchronously. By calling pack.get_future(), we get the associated future. Invoking the call operator on pack (pack()) executes the std::packaged_task and, therefore, executes the callable.

Dealing with std::packaged_task usually consists of four steps:

I. Wrap our work:

Press + to interact
std::packaged_task<int(int, int)> sumTask([](int a, int b){ return a + b; });

II. Create a future:

Press + to interact
std::future<int> sumResult= sumTask.get_future();

III. Perform the calculation:

Press + to interact
sumTask(2000, 11);

IV. Query the result:

Press + to interact
sumResult.get();

Here is an example ...