Namespaces
Variants
Views
Actions

std::packaged_task

From cppreference.com
< cpp‎ | thread
Revision as of 08:28, 7 February 2013 by Nate (Talk | contribs)

Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <future>
</td>

<td></td> <td></td> <tr class="t-dcl-sep"><td></td><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-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
template< class R, class Args... >
class packaged_task<R(Args...)>;
</td>

<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. 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

Template:cpp/thread/packaged task/dcl list constructorTemplate:cpp/thread/packaged task/dcl list destructorTemplate:cpp/thread/packaged task/dcl list operator=Template:cpp/thread/packaged task/dcl list validTemplate:cpp/thread/packaged task/dcl list swapTemplate:cpp/thread/packaged task/dcl list get futureTemplate:cpp/thread/packaged task/dcl list operator()Template:cpp/thread/packaged task/dcl list make ready at thread exitTemplate:cpp/thread/packaged task/dcl list reset
Getting the result
Execution

Non-member functions

Template:cpp/thread/packaged task/dcl list swap2

Helper classes

Template:cpp/thread/packaged task/dcl list uses allocator

Example

#include <iostream>
#include <cmath>
#include <thread>
#include <future>
 
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, 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);
    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

Template:cpp/thread/dcl list future