-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFuturePromiseII.cpp
43 lines (36 loc) · 998 Bytes
/
FuturePromiseII.cpp
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
#include <future>
#include <functional>
#include <iostream>
#include <thread>
#include <unistd.h>
#include <string>
template<typename F> auto async(F && func) -> std::future<decltype(func())>
{
using result_type = decltype(func());
auto promise = std::promise<result_type>();
auto future = promise.get_future();
std::thread( std::bind( [=](std::promise<result_type>& promise )
{
try
{
promise.set_value(func());
}
catch(...)
{
promise.set_exception(std::current_exception());
}
}, std::move(promise))).detach();
return std::move(future);
}
int main()
{
auto work_task =
[]()
{
/*working...*/ sleep(2); return std::string("Final Answer");
};
auto resp = async(work_task);
std::cout << resp.get() << std::endl;
}
// Note: Will not work with std::promise<void>. Needs some
// meta-template programming which is out of scope for this question.