Namespaces
Variants
Views
Actions

std::packaged_task

From cppreference.com
Defined in header <future>
template< class > class packaged_task; //not defined
(1) (since C++11)
template< class Function, class Args... >
class packaged_task<Function(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, 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

[edit] Member functions

constructs the task object
(public member function) [edit]
destructs the task object
(public member function) [edit]
moves the task object
(public member function) [edit]
checks if the task object has a valid function
(public member function) [edit]
swaps two task objects
(public member function) [edit]
Getting the result
returns a std::future associated with the promised result
(public member function) [edit]
Execution
executes the function
(public member function) [edit]
executes the function ensuring that the result is ready
only once the current thread exits
(public member function) [edit]
resets the state abandoning any stored results of previous executions
(public member function) [edit]

[edit] Non-member functions

specializes the std::swap algorithm
(function template) [edit]

[edit] Helper classes

specializes the std::uses_allocator type trait
(class template specialization) [edit]

[edit] Example

#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


[edit] See also

(C++11)
waits for a value that is set asynchronously
(class template) [edit]