-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_future.cpp
More file actions
56 lines (46 loc) · 1.54 KB
/
async_future.cpp
File metadata and controls
56 lines (46 loc) · 1.54 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
// see [N4045] Kohlhoff, Christopher, Library Foundations for Asynchronous
// Operations, Revision 2, 2014. and [N4242] Kohlhoff, Christopher, Executors
// and Asynchronous Operations, Revision 2, 2015.
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0113r0.html
// https://think-async.com/Asio/Documentation
// https://github.com/chriskohlhoff/asio/
#define BOOST_ASIO_NO_DEPRECATED
#include <boost/config.hpp>
#include <boost/asio/thread_pool.hpp>
#include <boost/asio/ts/executor.hpp>
#include <boost/chrono/chrono.hpp>
#include <boost/thread/thread.hpp>
#include <ctime>
#include <exception>
#include <iostream>
#if defined(BOOST_ASIO_HAS_STD_FUTURE)
# include <future>
#endif
using boost::asio::post;
using boost::asio::thread_pool;
using boost::asio::use_future;
// Run a (lambda) function asynchronously and wait for the result:
int main()
{
try {
thread_pool pool;
#if defined(BOOST_ASIO_HAS_STD_FUTURE)
std::future<int> f = post(pool, use_future([] {
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
// ...
if (std::time(NULL) % 2) {
throw std::runtime_error("Sorry, no answer at this odd time!");
}
return 42;
}));
std::cout << "Wait something ..., result = " << std::flush << f.get()
<< std::endl;
#else
throw std::runtime_error("Sorry, no future => no answer!")
#endif
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}