fork download
  1. #include <boost/asio.hpp>
  2. #include <functional>
  3. #include <thread>
  4.  
  5. using boost::asio::io_service;
  6.  
  7. class active_object
  8. {
  9. public:
  10. typedef std::function<void ()> completion_handler;
  11.  
  12. active_object()
  13. : work_(nullptr), strand_(service_)
  14. {
  15. }
  16. ~active_object()
  17. {
  18. // Must call stop before destructor is called
  19. assert(work_ == nullptr);
  20. }
  21.  
  22. void start(completion_handler handle_start)
  23. {
  24. assert(work_ == nullptr);
  25. work_ = new io_service::work(service_);
  26. runner_ = std::thread(&active_object::run_service, &service_);
  27. post(handle_start);
  28. }
  29.  
  30. void stop(completion_handler handle_stop)
  31. {
  32. // Cannot stop unless already started
  33. assert(work_ != nullptr);
  34. delete work_;
  35. work_ = nullptr;
  36. // Remaining jobs should complete
  37. // Add completion handler for stop to end of queue
  38. post(handle_stop);
  39. }
  40.  
  41. template <typename HandlerFunction>
  42. void post(HandlerFunction perform_operation)
  43. {
  44. strand_.post(perform_operation);
  45. }
  46.  
  47. private:
  48. static void run_service(io_service* service)
  49. {
  50. service->run();
  51. }
  52.  
  53. io_service service_;
  54. io_service::work* work_;
  55. io_service::strand strand_;
  56. std::thread runner_;
  57. };
  58.  
  59. #include <iostream>
  60.  
  61. active_object* s = new active_object;
  62.  
  63. // Executed in this order
  64. void handle_start();
  65. void foo();
  66. void bar();
  67. void do_stop();
  68. void handle_stop();
  69.  
  70. void handle_start()
  71. {
  72. s->post(foo);
  73. s->post(bar);
  74. s->post(do_stop);
  75. }
  76.  
  77. void foo()
  78. {
  79. std::cout << "foo called" << std::endl;
  80. }
  81.  
  82. void bar()
  83. {
  84. std::cout << "bar called" << std::endl;
  85. }
  86.  
  87. void do_stop()
  88. {
  89. std::cout << "stop called" << std::endl;
  90. s->stop(handle_stop);
  91. }
  92.  
  93. void handle_stop()
  94. {
  95. delete s;
  96. }
  97.  
  98. int main()
  99. {
  100. s->start(handle_start);
  101. std::cin.get();
  102. return 0;
  103. }
  104.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:1:26: fatal error: boost/asio.hpp: No such file or directory
compilation terminated.
stdout
Standard output is empty