Difference between revisions of "cpp/thread/packaged task"
From cppreference.com
(→Example: fmt) |
(err, this is the return type) |
||
Line 8: | Line 8: | ||
{{ddcl list item | num=2 | notes={{mark since c++11}} | | {{ddcl list item | num=2 | notes={{mark since c++11}} | | ||
template< class Function, class Args... > | template< class Function, class Args... > | ||
− | class packaged_task< | + | class packaged_task<R(Args...)>; |
}} | }} | ||
{{ddcl list end}} | {{ddcl list end}} |
Revision as of 06:01, 25 June 2012
Template:ddcl list begin <tr class="t-dsc-header">
<td>Defined in header
</td>
<future>
<td></td> <td></td> </tr> <tr class="t-dcl ">
<td >template< class > class packaged_task; //not defined
</td>
<td > (1) </td> <td > (since C++11) </td> </tr> <tr class="t-dcl ">
<td >template< class Function, class Args... >
class packaged_task<R(Args...)>;
</td>
class packaged_task<R(Args...)>;
<td > (2) </td> <td > (since C++11) </td> </tr> Template:ddcl list end
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, and its return value or exception thrown is stored in the 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
Non-member functions
Helper classes
Example
Run this code
#include <iostream> #include <future> #include <thread> int main() { std::packaged_task<int()> task([](){return 7;}); // wrap the function std::future<int> result = task.get_future(); // get a future std::thread(std::move(task)).detach(); // launch on a thread std::cout << "Waiting..."; result.wait(); std::cout << "Done!\nResult is " << result.get() << '\n'; }
Output:
Waiting...Done! Result is 7