The concurrency support module supports a concept called task. A task is work that happens concurrently across threads. A concurrent task can be created using the packaged_task class. The packaged_task class conveniently connects the thread function, the corresponding promise, and feature objects.
Let's understand the use of packaged_task with a simple example. The following program gives us an opportunity to taste a bit of functional programming with lambda expressions and functions:
#include <iostream>
#include <future>
#include <promise>
#include <thread>
#include <functional>
using namespace std;
int main ( ) {
packaged_task<int (int, int)>
addTask ( [] ( int firstInput, int secondInput ) {
return firstInput + secondInput;
} );
future<int> output = addTask.get_future( );
addTask ( 15, 10 );
cout << "The sum of 15 + 10 is " << output.get() << endl;
return 0;
}
In the previously shown program, I created a packaged_task instance called addTask. The packaged_task< int (int,int)> instance implies that the add task will return an integer and take two integer arguments:
addTask ( [] ( int firstInput, int secondInput ) {
return firstInput + secondInput;
});
The preceding code snippet indicates it is a lambda function that is defined anonymously.
The interesting part is that the addTask( ) call in main.cpp appears like a regular function call. The future<int> object is extracted from the packaged_task instance addTask, which is then used to retrieve the output of the addTask via the future object instance, that is, the get() method.