sequencer
thread_pool.hpp
Go to the documentation of this file.
1 #pragma once
2 
4 
5 #include <atomic>
6 #include <condition_variable>
7 #include <mutex>
8 #include <thread>
9 #include <vector>
10 
11 namespace sequencer
12 {
13  template < class Task >
15  {
16  using Result = std::decay_t< decltype( std::declval< Task >()() ) >;
17 
18  struct thread_with_queue_t
19  {
20  std::thread thread{};
23  };
24 
25  using size_type = typename std::vector< thread_with_queue_t >::size_type;
26 
27  public:
28  explicit thread_pool_t( size_type size ) : threads_( size )
29  {
30  for ( size_type i = 0; i < size; ++i )
31  {
32  threads_[ i ].thread = std::thread( [this, i] {
33  while ( !stopped_ )
34  {
35  {
36  std::unique_lock lock{sleep_mutex_};
37  sleep_condition_.wait( lock, [this] { return !sleeping_; } );
38  }
39 
40  const auto task = threads_[ i ].task_queue.try_pop();
41  if ( task )
42  {
43  threads_[ i ].result_queue.push( ( *task )() );
44  }
45  }
46  } );
47  }
48  }
49 
51  {
52  stopped_ = true;
53  sleeping_ = false;
54  sleep_condition_.notify_all();
55  for ( auto& entry : threads_ )
56  {
57  entry.thread.join();
58  }
59  }
60 
61  auto& task_queue( size_type idx ) noexcept
62  {
63  return threads_[ idx ].task_queue;
64  }
65 
66  auto& result_queue( size_type idx ) noexcept
67  {
68  return threads_[ idx ].result_queue;
69  }
70 
71  void stop()
72  {
73  std::lock_guard lock{sleep_mutex_};
74  sleeping_ = true;
75  }
76 
77  void start()
78  {
79  std::lock_guard lock{sleep_mutex_};
80  sleeping_ = false;
81  sleep_condition_.notify_all();
82  }
83 
84  private:
85  std::vector< thread_with_queue_t > threads_;
86  std::condition_variable sleep_condition_;
87  std::mutex sleep_mutex_;
88  bool sleeping_{true};
89  std::atomic_bool stopped_{false};
90  };
91 } // namespace sequencer
~thread_pool_t()
Definition: thread_pool.hpp:50
thread_pool_t(size_type size)
Definition: thread_pool.hpp:28
auto & task_queue(size_type idx) noexcept
Definition: thread_pool.hpp:61
Definition: thread_pool.hpp:14
void start()
Definition: thread_pool.hpp:77
void stop()
Definition: thread_pool.hpp:71
auto & result_queue(size_type idx) noexcept
Definition: thread_pool.hpp:66