Search⌘ K

Introduction to std::packaged_task

Explore how to use std::packaged_task to wrap callable objects for asynchronous execution in C++. Learn the four key steps: wrapping work, creating futures, performing calculations, and retrieving results. Understand how to use futures to collect asynchronous task outcomes in multithreaded programs.

We'll cover the following...

std::packaged_task pack is a wrapper for a callable in order for it to be invoked asynchronously. By calling pack.get_future() you 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 your work:

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

II. Create a future:

C++
std::future<int> sumResult= sumTask.get_future();

III. Perform the calculation:

C++
sumTask(2000, 11);

IV. Query the result:

C++
sumResult.get();

Here is an example showing the four ...