system_context.ipp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // impl/system_context.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef BOOST_ASIO_IMPL_SYSTEM_CONTEXT_IPP
  11. #define BOOST_ASIO_IMPL_SYSTEM_CONTEXT_IPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #include <boost/asio/system_context.hpp>
  17. #include <boost/asio/detail/push_options.hpp>
  18. namespace boost {
  19. namespace asio {
  20. struct system_context::thread_function
  21. {
  22. detail::scheduler* scheduler_;
  23. void operator()()
  24. {
  25. boost::system::error_code ec;
  26. scheduler_->run(ec);
  27. }
  28. };
  29. system_context::system_context()
  30. : scheduler_(add_scheduler(new detail::scheduler(*this, 0, false)))
  31. {
  32. scheduler_.work_started();
  33. thread_function f = { &scheduler_ };
  34. std::size_t num_threads = detail::thread::hardware_concurrency() * 2;
  35. threads_.create_threads(f, num_threads ? num_threads : 2);
  36. }
  37. system_context::~system_context()
  38. {
  39. scheduler_.work_finished();
  40. scheduler_.stop();
  41. threads_.join();
  42. }
  43. void system_context::stop()
  44. {
  45. scheduler_.stop();
  46. }
  47. bool system_context::stopped() const BOOST_ASIO_NOEXCEPT
  48. {
  49. return scheduler_.stopped();
  50. }
  51. void system_context::join()
  52. {
  53. scheduler_.work_finished();
  54. threads_.join();
  55. }
  56. detail::scheduler& system_context::add_scheduler(detail::scheduler* s)
  57. {
  58. detail::scoped_ptr<detail::scheduler> scoped_impl(s);
  59. boost::asio::add_service<detail::scheduler>(*this, scoped_impl.get());
  60. return *scoped_impl.release();
  61. }
  62. } // namespace asio
  63. } // namespace boost
  64. #include <boost/asio/detail/pop_options.hpp>
  65. #endif // BOOST_ASIO_IMPL_SYSTEM_CONTEXT_IPP