Difference between revisions of "cpp/thread/packaged task"
From cppreference.com
Line 76: | Line 76: | ||
void task_thread() | void task_thread() | ||
{ | { | ||
− | std::packaged_task<int(int,int)> task(std::pow); | + | std::packaged_task<int(int,int)> task(std::pow<double, double>); |
std::future<int> result = task.get_future(); | std::future<int> result = task.get_future(); | ||
Revision as of 16:07, 25 October 2013
Defined in header <future>
|
||
template< class > class packaged_task; //not defined |
(1) | (since C++11) |
template< class R, class Args... > class packaged_task<R(Args...)>; |
(2) | (since C++11) |
The class template std::packaged_task
wraps any callable target (function, lambda expression, bind expression, or another function object) so that it can be invoked asynchronously. Its return value or exception thrown is stored in a shared state which can be accessed through std::future objects.
Just like std::function, std::packaged_task
is a polymorphic, allocator-aware container: the stored callable target may be allocated on heap or with a provided allocator.
Contents |
Member functions
constructs the task object (public member function) | |
destructs the task object (public member function) | |
moves the task object (public member function) | |
checks if the task object has a valid function (public member function) | |
swaps two task objects (public member function) | |
Getting the result | |
returns a std::future associated with the promised result (public member function) | |
Execution | |
executes the function (public member function) | |
executes the function ensuring that the result is ready only once the current thread exits (public member function) | |
resets the state abandoning any stored results of previous executions (public member function) |
Non-member functions
specializes the std::swap algorithm (function template) |
Helper classes
(C++11) (until C++17) |
specializes the std::uses_allocator type trait (class template specialization) |
Example
Run this code
#include <iostream> #include <cmath> #include <thread> #include <future> #include <functional> void task_lambda() { std::packaged_task<int(int,int)> task([](int a, int b) { return std::pow(a, b); }); std::future<int> result = task.get_future(); task(2, 9); std::cout << "task_lambda:\t" << result.get() << '\n'; } void task_bind() { std::packaged_task<int()> task(std::bind(std::pow<double, double>, 2, 11)); std::future<int> result = task.get_future(); task(); std::cout << "task_bind:\t" << result.get() << '\n'; } void task_thread() { std::packaged_task<int(int,int)> task(std::pow<double, double>); std::future<int> result = task.get_future(); std::thread task_td(std::move(task), 2, 10); task_td.join(); std::cout << "task_thread:\t" << result.get() << '\n'; } int main() { task_lambda(); task_bind(); task_thread(); }
Output:
task_lambda: 512 task_bind: 2048 task_thread: 1024
See also
(C++11) |
waits for a value that is set asynchronously (class template) |