system_context.ipp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // impl/system_context.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2021 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. #if !defined(BOOST_ASIO_NO_EXCEPTIONS)
  26. try
  27. {
  28. #endif// !defined(BOOST_ASIO_NO_EXCEPTIONS)
  29. boost::system::error_code ec;
  30. scheduler_->run(ec);
  31. #if !defined(BOOST_ASIO_NO_EXCEPTIONS)
  32. }
  33. catch (...)
  34. {
  35. std::terminate();
  36. }
  37. #endif// !defined(BOOST_ASIO_NO_EXCEPTIONS)
  38. }
  39. };
  40. system_context::system_context()
  41. : scheduler_(add_scheduler(new detail::scheduler(*this, 0, false)))
  42. {
  43. scheduler_.work_started();
  44. thread_function f = { &scheduler_ };
  45. num_threads_ = detail::thread::hardware_concurrency() * 2;
  46. num_threads_ = num_threads_ ? num_threads_ : 2;
  47. threads_.create_threads(f, num_threads_);
  48. }
  49. system_context::~system_context()
  50. {
  51. scheduler_.work_finished();
  52. scheduler_.stop();
  53. threads_.join();
  54. }
  55. void system_context::stop()
  56. {
  57. scheduler_.stop();
  58. }
  59. bool system_context::stopped() const BOOST_ASIO_NOEXCEPT
  60. {
  61. return scheduler_.stopped();
  62. }
  63. void system_context::join()
  64. {
  65. scheduler_.work_finished();
  66. threads_.join();
  67. }
  68. detail::scheduler& system_context::add_scheduler(detail::scheduler* s)
  69. {
  70. detail::scoped_ptr<detail::scheduler> scoped_impl(s);
  71. boost::asio::add_service<detail::scheduler>(*this, scoped_impl.get());
  72. return *scoped_impl.release();
  73. }
  74. } // namespace asio
  75. } // namespace boost
  76. #include <boost/asio/detail/pop_options.hpp>
  77. #endif // BOOST_ASIO_IMPL_SYSTEM_CONTEXT_IPP