thread_group.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. //
  2. // detail/thread_group.hpp
  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_DETAIL_THREAD_GROUP_HPP
  11. #define BOOST_ASIO_DETAIL_THREAD_GROUP_HPP
  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/detail/scoped_ptr.hpp>
  17. #include <boost/asio/detail/thread.hpp>
  18. #include <boost/asio/detail/push_options.hpp>
  19. namespace boost {
  20. namespace asio {
  21. namespace detail {
  22. class thread_group
  23. {
  24. public:
  25. // Constructor initialises an empty thread group.
  26. thread_group()
  27. : first_(0)
  28. {
  29. }
  30. // Destructor joins any remaining threads in the group.
  31. ~thread_group()
  32. {
  33. join();
  34. }
  35. // Create a new thread in the group.
  36. template <typename Function>
  37. void create_thread(Function f)
  38. {
  39. first_ = new item(f, first_);
  40. }
  41. // Create new threads in the group.
  42. template <typename Function>
  43. void create_threads(Function f, std::size_t num_threads)
  44. {
  45. for (std::size_t i = 0; i < num_threads; ++i)
  46. create_thread(f);
  47. }
  48. // Wait for all threads in the group to exit.
  49. void join()
  50. {
  51. while (first_)
  52. {
  53. first_->thread_.join();
  54. item* tmp = first_;
  55. first_ = first_->next_;
  56. delete tmp;
  57. }
  58. }
  59. // Test whether the group is empty.
  60. bool empty() const
  61. {
  62. return first_ == 0;
  63. }
  64. private:
  65. // Structure used to track a single thread in the group.
  66. struct item
  67. {
  68. template <typename Function>
  69. explicit item(Function f, item* next)
  70. : thread_(f),
  71. next_(next)
  72. {
  73. }
  74. boost::asio::detail::thread thread_;
  75. item* next_;
  76. };
  77. // The first thread in the group.
  78. item* first_;
  79. };
  80. } // namespace detail
  81. } // namespace asio
  82. } // namespace boost
  83. #include <boost/asio/detail/pop_options.hpp>
  84. #endif // BOOST_ASIO_DETAIL_THREAD_GROUP_HPP