• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
11 #ifndef BOOST_ASIO_DETAIL_THREAD_GROUP_HPP
12 #define BOOST_ASIO_DETAIL_THREAD_GROUP_HPP
13 
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
15 # pragma once
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
17 
18 #include <boost/asio/detail/config.hpp>
19 #include <boost/asio/detail/scoped_ptr.hpp>
20 #include <boost/asio/detail/thread.hpp>
21 
22 #include <boost/asio/detail/push_options.hpp>
23 
24 namespace boost {
25 namespace asio {
26 namespace detail {
27 
28 class thread_group
29 {
30 public:
31   // Constructor initialises an empty thread group.
thread_group()32   thread_group()
33     : first_(0)
34   {
35   }
36 
37   // Destructor joins any remaining threads in the group.
~thread_group()38   ~thread_group()
39   {
40     join();
41   }
42 
43   // Create a new thread in the group.
44   template <typename Function>
create_thread(Function f)45   void create_thread(Function f)
46   {
47     first_ = new item(f, first_);
48   }
49 
50   // Create new threads in the group.
51   template <typename Function>
create_threads(Function f,std::size_t num_threads)52   void create_threads(Function f, std::size_t num_threads)
53   {
54     for (std::size_t i = 0; i < num_threads; ++i)
55       create_thread(f);
56   }
57 
58   // Wait for all threads in the group to exit.
join()59   void join()
60   {
61     while (first_)
62     {
63       first_->thread_.join();
64       item* tmp = first_;
65       first_ = first_->next_;
66       delete tmp;
67     }
68   }
69 
70   // Test whether the group is empty.
empty() const71   bool empty() const
72   {
73     return first_ == 0;
74   }
75 
76 private:
77   // Structure used to track a single thread in the group.
78   struct item
79   {
80     template <typename Function>
itemboost::asio::detail::thread_group::item81     explicit item(Function f, item* next)
82       : thread_(f),
83         next_(next)
84     {
85     }
86 
87     boost::asio::detail::thread thread_;
88     item* next_;
89   };
90 
91   // The first thread in the group.
92   item* first_;
93 };
94 
95 } // namespace detail
96 } // namespace asio
97 } // namespace boost
98 
99 #include <boost/asio/detail/pop_options.hpp>
100 
101 #endif // BOOST_ASIO_DETAIL_THREAD_GROUP_HPP
102