A packaged_task is a wrapper for any callable target (function, bind, lambda, or other function object). It allows for asynchronous execution with the result available in a future object. It is similar to std::function, but automatically transfers its results to a future object.
For example:
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
using namespace std;
int countdown (int from, int to) {
for (int i = from; i != to; --i) {
cout << i << 'n';
this_thread::sleep_for(chrono::seconds(1));
}
cout << "Finished countdown.n";
return from - to;
}
int main () {
packaged_task<int(int, int)> task(countdown);
future<int> result = task.get_future();
thread t (std::move(task), 10, 0);
// Other logic.
int value = result.get();
cout << "The countdown lasted for " << value << " seconds.n";
t.join();
return 0;
}
This preceding code implements a simple countdown feature, counting down from 10 to 0. After creating the task and obtaining a reference to its future object, we push it onto a thread along with the parameters of the worker function.
The result from the countdown worker thread becomes available as soon as it finishes. We can use the future object's waiting functions here the same way as for a promise.