thread_group.hpp 1.9 KB

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