Packaged Task
std::packaged_task
-
Defined in
<future> -
Encapsulates a task
- A callable object for the task's code
- An
std::promisefor the result of the task
-
Provided a higher level of abstraction
-
Template class
- The parameter is the callable object's signature
// std::packaged_task object // The callable object takes int and int arguments. // It returns int std::packaged_task<int(int, int)> ptask(...); -
The constructor takes the callable object as argument
std::packaged_task Interface
- Functor class
- Overloaded operator()
- Invokes the callable object
- Stores the return value in the promise object
get_future()- Returns the
std::futureobject associated with the promise
- Returns the
std::packaged_taskis a move-only class
Using an std::packaged_task Object
- Pass a callable object to the constructor
- The packaged task starts when operator() is called
- In the same thread, by calling it directly
- In a new thread, by passing the task to
std::thread's constructor
- We call
get_future() - We call
get()on the returned future objectOr wait()and friends
Example of std::packaged_task in Same Thread
// Packaged task using lambda expression
std::packaged_task<int(int, int)> ptask([](int a, int b) {
return a + b;
});
// The future associated with the packaged_task's promise
std::future<int> fut = ptask.get_future();
// invoke the packaged task in this thread
ptask(6, 7);
// Call get() to recieve the result
fut.get();
Example of std::packaged_task in New Thread
// Create a thread
// The packaged task will be its entry point
std::thread thr(std::move(ptask), 6, 7);
thr.join();
Advantages of std::packaged_task
- Avoids boilerplate code
- Create
std::promiseobject - Pass it to task function
- Create
Applications of std::packaged_task
-
Create a container of packaged_task objects
- The threads do not start up until we are ready for them
-
Useful for managing threads
- Each task can be run on a specified thread
- Thread scheduler runs threads in a certain order
- Thread pool consists of threads waiting for work to arrive