Furrent
group.hpp
Go to the documentation of this file.
1 
8 #pragma once
9 
10 #include <functional>
11 #include <mutex>
12 #include <optional>
13 #include <thread>
14 #include <vector>
15 
16 namespace fur::mt {
17 
19 class Runner {
21  std::mutex& _mutex;
23  bool& _should_terminate;
24 
25  public:
26  Runner(std::mutex& mutex, bool& _should_terminate);
27 
29  bool alive();
30 };
31 
33 template <typename State>
34 class ThreadGroup {
38  using ThreadFn = std::function<void(Runner, State&, size_t)>;
39 
41  std::vector<std::thread> _threads;
43  std::vector<State> _states;
45  ThreadFn _thread_fn;
47  std::mutex _mutex;
49  bool _should_terminate;
50 
51  public:
53  ThreadGroup();
55  virtual ~ThreadGroup();
56 
57  //===========================================================================
58  // This object is not copyable and not movable because of the mutex
59 
60  ThreadGroup(ThreadGroup&) = delete;
61  ThreadGroup& operator=(ThreadGroup&) = delete;
62  ThreadGroup(ThreadGroup&&) noexcept = delete;
63  ThreadGroup& operator=(ThreadGroup&&) noexcept = delete;
64 
65  //===========================================================================
66 
68  void launch(ThreadFn fn, int64_t max_worker_threads = 0);
69 
71  void terminate();
72 
74  std::vector<State>& get_states();
75 
77  [[nodiscard]] int64_t get_worker_count() const;
78 
79  private:
81  void thread_main(int64_t index);
82 };
83 
84 } // namespace fur::mt
85 
86 #include <mt/group.inl>
fur::mt::ThreadGroup
Manages the execution of a group of threads.
Definition: group.hpp:34
fur::mt::Runner::alive
bool alive()
True if threads should continue executing.
Definition: group.cpp:8
fur::mt::ThreadGroup::operator=
ThreadGroup & operator=(ThreadGroup &)=delete
fur::mt::ThreadGroup::get_worker_count
int64_t get_worker_count() const
Get total number of workers.
Definition: group.inl:52
fur::mt::ThreadGroup::get_states
std::vector< State > & get_states()
Obtain threads state.
Definition: group.inl:47
fur::mt
Definition: group.cpp:3
group.inl
fur::mt::ThreadGroup::terminate
void terminate()
Terminate thread execution, this operation is irrecuperable.
Definition: group.inl:38
fur::mt::ThreadGroup::ThreadGroup
ThreadGroup()
Create disabled thread group.
Definition: group.inl:8
fur::mt::Runner::Runner
Runner(std::mutex &mutex, bool &_should_terminate)
Definition: group.cpp:5
fur::mt::Runner
Used to control threads execution.
Definition: group.hpp:19
fur::mt::ThreadGroup::launch
void launch(ThreadFn fn, int64_t max_worker_threads=0)
Create threads and begin execution.
Definition: group.inl:16
fur::mt::ThreadGroup::~ThreadGroup
virtual ~ThreadGroup()
Stops and joins all threads.
Definition: group.inl:11