system_context.ipp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // impl/system_context.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2025 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, false))),
  42. threads_(std::allocator<void>())
  43. {
  44. scheduler_.work_started();
  45. thread_function f = { &scheduler_ };
  46. num_threads_ = detail::thread::hardware_concurrency() * 2;
  47. num_threads_ = num_threads_ ? num_threads_ : 2;
  48. threads_.create_threads(f, num_threads_);
  49. }
  50. system_context::~system_context()
  51. {
  52. scheduler_.work_finished();
  53. scheduler_.stop();
  54. threads_.join();
  55. }
  56. void system_context::stop()
  57. {
  58. scheduler_.stop();
  59. }
  60. bool system_context::stopped() const noexcept
  61. {
  62. return scheduler_.stopped();
  63. }
  64. void system_context::join()
  65. {
  66. scheduler_.work_finished();
  67. threads_.join();
  68. }
  69. detail::scheduler& system_context::add_scheduler(detail::scheduler* s)
  70. {
  71. detail::scoped_ptr<detail::scheduler> scoped_impl(s);
  72. boost::asio::add_service<detail::scheduler>(*this, scoped_impl.get());
  73. return *scoped_impl.release();
  74. }
  75. } // namespace asio
  76. } // namespace boost
  77. #include <boost/asio/detail/pop_options.hpp>
  78. #endif // BOOST_ASIO_IMPL_SYSTEM_CONTEXT_IPP