July 2017
Intermediate to advanced
244 pages
6h 33m
English
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. ...Read now
Unlock full access