class template
<future>
std::packaged_tasktemplate <class T> packaged_task; // undefinedtemplate <class Ret, class... Args> class packaged_task<Ret(Args...)>;
Packaged task
A packaged_task wraps a callable element and allows its result to be retrieved asynchronously.It is similar to std::function, but transferring its result automatically to a future object.
The object contains internally two elements:
The lifetime of the shared state lasts at least until the last object with which it is associated releases it or is destroyed. Therefore it can survive the packaged_task object that obtained it in the first place if associated also to a future.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// packaged_task example
#include <iostream> // std::cout
#include <future> // std::packaged_task, std::future
#include <chrono> // std::chrono::seconds
#include <thread> // std::thread, std::this_thread::sleep_for
// count down taking a second for each value:
int countdown (int from, int to) {
for (int i=from; i!=to; --i) {
std::cout << i << '\n';
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Lift off!\n";
return from-to;
}
int main ()
{
std::packaged_task<int(int,int)> tsk (countdown); // set up packaged_task
std::future<int> ret = tsk.get_future(); // get future
std::thread th (std::move(tsk),10,0); // spawn thread to count down from 10 to 0
// ...
int value = ret.get(); // wait for the task to finish and get result
std::cout << "The countdown lasted for " << value << " seconds.\n";
th.join();
return 0;
}
10 9 8 7 6 5 4 3 2 1 Lift off! The countdown lasted for 10 seconds.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4