pausable_thread_loop.hpp
1 
6 #pragma once
7 
8 #include <atomic>
9 #include <cstdint>
10 #include <functional>
11 #include <thread>
12 
13 #include <rapidsmpf/utils.hpp>
14 
15 namespace rapidsmpf::detail {
22  public:
41  std::function<void()> func, Duration sleep = std::chrono::seconds{0}
42  );
43  ~PausableThreadLoop() noexcept;
44 
53  [[nodiscard]] bool is_running() const noexcept;
54 
68  void pause_nb() noexcept;
69 
78  void pause() noexcept;
79 
87  bool resume() noexcept;
88 
100  bool stop() noexcept;
101 
102  private:
106  enum State : std::uint8_t {
107  Stopped,
108  Stopping,
109  Paused,
110  Pausing,
111  Running,
112  };
113 
114  // State transition matrix:
115  // | cur_state | | | nxt_state | | || Ops |
116  // | |---------|----------|-----------|----------|---------|| |
117  // | | STOPPED | STOPPING | PAUSED | PAUSING | RUNNING ||---------|
118  // |-----------|---------|----------|-----------|----------|---------|| e_loop |
119  // | STOPPED | no_op | X | X | X | X || pause |
120  // | STOPPING | e_loop | no_op | X | X | X || resume |
121  // | PAUSED | X | stop | no_op | X | resume || stop |
122  // | PAUSING | e_loop | stop | e_loop | no_op | resume || no_op |
123  // | RUNNING | X | stop | X | pause | no_op || X |
124  //
125  // pause():
126  // RUNNING -> PAUSING
127  // stop():
128  // RUNNING -> STOPPING | PAUSING -> STOPPING | PAUSED -> STOPPING
129  // resume():
130  // PAUSING -> RUNNING | PAUSED -> RUNNING
131  // automatic transition via event loop:
132  // PAUSING -> PAUSED
133  // STOPPING -> STOPPED
134 
135  std::thread thread_;
136  std::atomic<State> state_{State::Paused};
137 };
138 
139 } // namespace rapidsmpf::detail
A thread loop that can be paused, resumed, and stopped.
PausableThreadLoop(std::function< void()> func, Duration sleep=std::chrono::seconds{0})
Constructs a thread to run the specified function in a loop.
void pause() noexcept
Pauses the execution of the thread.
bool is_running() const noexcept
Checks if the thread is currently running (not paused or stopped).
bool resume() noexcept
Resumes execution of the thread after being paused.
void pause_nb() noexcept
Pauses the execution of the thread.
bool stop() noexcept
Stops the execution of the thread and joins it.