-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathf-pt.cpp
More file actions
73 lines (56 loc) · 1.78 KB
/
Copy pathf-pt.cpp
File metadata and controls
73 lines (56 loc) · 1.78 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2709.html
#include <thread>
#include <future>
#include <cassert>
#include <memory> // unique_ptr
int calculate_the_answer_to_life_the_universe_and_everything()
{
return 42;
}
template<typename F>
std::future<typename std::result_of<F()>::type> spawn_task1(F f)
{
typedef typename std::result_of<F()>::type result_type;
std::packaged_task<result_type()> task(std::move(f));
std::future<result_type> res(task.get_future());
std::thread(std::move(task));
return res;
}
template<typename F>
std::future<typename std::result_of<F()>::type> spawn_task2(F f)
{
typedef typename std::result_of<F()>::type result_type;
struct local_task
{
std::promise<result_type> promise;
F func;
local_task(local_task const& other)=delete;
local_task(F func_): func(func_) {}
local_task(local_task&& other): promise(std::move(other.promise)), func(std::move(other.func)) {}
void op() // GB was operator
{
try {
promise.set_value(f());
} catch(...) {
promise.set_exception(std::current_exception());
}
}
};
local_task task(std::move(f));
std::future<result_type> res(task.promise.get_future());
std::thread(std::move(task));
return res;
}
int main(int argc, char**argv)
{
std::packaged_task<int()> pt(calculate_the_answer_to_life_the_universe_and_everything);
auto fi=pt.get_future();
std::thread task(std::move(pt)); // launch task on a thread
fi.wait(); // wait for it to finish
// assert(fi.is_ready());
// assert(fi.has_value());
// assert(!fi.has_exception());
// assert(fi.get_state()==std::future_state::ready);
assert(fi.get()==42);
task.join();
}