프로그래밍/코드 조각

asio::io_service + promise + future background worker

제페 2016. 2. 15. 07:45
반응형

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
#include <iostream>
#include <future>
#include <type_traits>
#include <boost/asio.hpp>
 
using namespace boost::asio;
 
io_service ios;
io_service::work work{ ios };
 
template < typename Func >
auto post(Func&& func)
{
  using return_type = decltype(func());
  
  auto promise = std::make_shared<std::promise<return_type>>();
  auto future = promise->get_future();
 
  ios.post
    (
      [promise, func]
      {
        promise->set_value(func());
      }
    );
 
  return future;
}
 
 
int main()
{
  auto async_res = std::async
    (
      std::launch::async, 
      [] 
      {
        ios.run();
      }
    );
 
  int a = 10;
  int b = 20;
 
  auto future = post([a, b] { return a*b; });
 
  std::cout << future.get() << std::endl;
 
  return 0;
}
cs



반응형