system_context.ipp 1.9 KB

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