Fray Engine
Loading...
Searching...
No Matches
thread_manager.hpp
Go to the documentation of this file.
1#ifndef FRAY_THREAD_MANAGER_HPP
2#define FRAY_THREAD_MANAGER_HPP
3
4#include <atomic>
5#include <chrono>
6#include <condition_variable>
7#include <cstdint>
8#include <deque>
9#include <exception>
10#include <functional>
11#include <map>
12#include <memory>
13#include <mutex>
14#include <string>
15#include <thread>
16#include <utility>
17#include <vector>
18
19#include "log_manager.hpp"
20
21namespace fray
22{
23 namespace threads
24 {
30 {
31 private:
33 struct State
34 {
35 std::mutex mutex;
36 std::condition_variable wake;
37 bool stop = false;
38 };
39
40 std::shared_ptr<State> _state = std::make_shared<State>();
41
42 public:
44 bool stopRequested() const
45 {
46 std::lock_guard<std::mutex> lock(_state->mutex);
47 return _state->stop;
48 }
49
55 template<typename Rep, typename Period>
56 bool waitFor(
57 const std::chrono::duration<Rep, Period>& duration) const
58 {
59 std::unique_lock<std::mutex> lock(_state->mutex);
60 return _state->wake.wait_for(lock, duration, [this] { return _state->stop; });
61 }
62
64 void requestStop() const
65 {
66 {
67 std::lock_guard<std::mutex> lock(_state->mutex);
68 _state->stop = true;
69 }
70 _state->wake.notify_all();
71 }
72 };
73
79 {
80 private:
82 std::mutex _mutex;
84 std::condition_variable _wake;
86 std::deque<std::function<void()>> _tasks;
88 bool _shutdown = false;
89
90 public:
96 bool post(
97 std::function<void()> task)
98 {
99 {
100 std::lock_guard<std::mutex> lock(_mutex);
101 if (_shutdown)
102 return false;
103 _tasks.push_back(std::move(task));
104 }
105 _wake.notify_one();
106 return true;
107 }
108
110 void shutdown()
111 {
112 {
113 std::lock_guard<std::mutex> lock(_mutex);
114 _shutdown = true;
115 }
116 _wake.notify_all();
117 }
118
124 void run(
125 const std::function<bool()>& keepAlive = nullptr)
126 {
127 for (;;)
128 {
129 std::function<void()> task;
130 {
131 std::unique_lock<std::mutex> lock(_mutex);
132 const auto finished = [&] { return _shutdown && !(keepAlive && keepAlive()); };
133 _wake.wait_for(lock, std::chrono::milliseconds(50),
134 [&] { return !_tasks.empty() || finished(); });
135 if (_tasks.empty())
136 {
137 if (finished())
138 return;
139 continue;
140 }
141 task = std::move(_tasks.front());
142 _tasks.pop_front();
143 }
144 try
145 {
146 task();
147 }
148 catch (const std::exception& error)
149 {
150 fray::log::engineError("Thread task failed: %s", error.what());
151 }
152 catch (...)
153 {
154 fray::log::engineError("Thread task failed with an unknown exception.");
155 }
156 }
157 }
158 };
159
167 {
168 public:
170 using Id = std::uint64_t;
171
172 private:
174 struct Entry
175 {
177 std::string name;
179 std::thread thread;
183 std::shared_ptr<std::atomic<bool>> finished;
184 };
185
186 mutable std::mutex _mutex;
188 std::map<Id, Entry> _entries;
191
192 public:
194 ThreadManager() = default;
197 const ThreadManager&) = delete;
200 const ThreadManager&) = delete;
201
204 {
205 const std::vector<std::string> remaining = runningNames();
206 if (!remaining.empty())
207 {
208 std::string names;
209 for (const std::string& name : remaining)
210 names += (names.empty() ? "" : ", ") + name;
211 fray::log::engineWarn("Waiting on %zu thread(s) to finish: %s", remaining.size(), names.c_str());
212 }
213 stopAll();
214 joinAll();
215 }
216
225 const std::string& name,
226 std::function<void(StopToken)> body)
227 {
228 StopToken token;
229 auto finished = std::make_shared<std::atomic<bool>>(false);
230 std::thread thread([name, body = std::move(body), token, finished]
231 {
232 try
233 {
234 body(token);
235 }
236 catch (const std::exception& error)
237 {
238 fray::log::engineError("Thread %s failed: %s", name.c_str(), error.what());
239 }
240 catch (...)
241 {
242 fray::log::engineError("Thread %s failed with an unknown exception.", name.c_str());
243 }
244 finished->store(true);
245 });
246 std::lock_guard<std::mutex> lock(_mutex);
247 const Id id = _next++;
248 _entries.emplace(id, Entry{name, std::move(thread), token, finished});
249 return id;
250 }
251
258 Id id) const
259 {
260 std::lock_guard<std::mutex> lock(_mutex);
261 const auto found = _entries.find(id);
262 return found != _entries.end() && !found->second.finished->load();
263 }
264
266 std::size_t running() const
267 {
268 std::lock_guard<std::mutex> lock(_mutex);
269 std::size_t count = 0;
270 for (const auto& entry : _entries)
271 if (!entry.second.finished->load())
272 ++count;
273 return count;
274 }
275
277 std::vector<std::string> runningNames() const
278 {
279 std::lock_guard<std::mutex> lock(_mutex);
280 std::vector<std::string> names;
281 for (const auto& entry : _entries)
282 if (!entry.second.finished->load())
283 names.push_back(entry.second.name);
284 return names;
285 }
286
292 Id id)
293 {
294 std::lock_guard<std::mutex> lock(_mutex);
295 const auto found = _entries.find(id);
296 if (found != _entries.end())
297 found->second.token.requestStop();
298 }
299
306 bool join(
307 Id id)
308 {
309 std::thread thread;
310 {
311 std::lock_guard<std::mutex> lock(_mutex);
312 const auto found = _entries.find(id);
313 if (found == _entries.end())
314 return true;
315 if (found->second.thread.get_id() == std::this_thread::get_id())
316 return false;
317 thread = std::move(found->second.thread);
318 _entries.erase(found);
319 }
320 if (thread.joinable())
321 thread.join();
322 return true;
323 }
324
326 void stopAll()
327 {
328 std::lock_guard<std::mutex> lock(_mutex);
329 for (auto& entry : _entries)
330 entry.second.token.requestStop();
331 }
332
334 void joinAll()
335 {
336 std::vector<Id> ids;
337 {
338 std::lock_guard<std::mutex> lock(_mutex);
339 for (const auto& entry : _entries)
340 ids.push_back(entry.first);
341 }
342 for (const Id id : ids)
343 join(id);
344 }
345 };
346 }
347}
348
349#endif
Cooperative cancellation shared by every copy of a token. Copies share one state guarded by an intern...
void requestStop() const
Requests a stop on all copies and wakes any waitFor() callers. Safe from any thread; idempotent.
bool waitFor(const std::chrono::duration< Rep, Period > &duration) const
Sleeps for up to duration; returns true as soon as a stop is requested.
std::shared_ptr< State > _state
bool stopRequested() const
True once requestStop() was called on any copy. Briefly takes the token's mutex.
A task loop that runs on one thread. Other threads post work to it. Tasks run one at a time in postin...
bool post(std::function< void()> task)
Queues a task to run on the queue's thread. Never waits for it to run.
void run(const std::function< bool()> &keepAlive=nullptr)
Runs queued tasks until shutdown() was called, the queue is empty and keepAlive() is false....
std::condition_variable _wake
std::deque< std::function< void()> > _tasks
void shutdown()
Stops accepting new tasks; run() returns once the queue is empty (and keepAlive is false)....
ThreadManager()=default
Creates an empty manager.
~ThreadManager()
Warns about threads still running, requests stop on all of them, then joins them all (blocks until th...
ThreadManager(const ThreadManager &)=delete
Not copyable: it owns threads.
void requestStop(Id id)
Asks one thread to stop by triggering its StopToken. Does not wait; the body must poll the token.
bool join(Id id)
Blocks until the thread ends, then forgets it. Joining the calling thread is refused....
ThreadManager & operator=(const ThreadManager &)=delete
Not copy-assignable: it owns threads.
void joinAll()
Joins every registered thread (blocks until all have ended); a thread cannot join itself,...
std::size_t running() const
Number of registered threads whose body has not yet returned.
std::map< Id, Entry > _entries
bool running(Id id) const
Whether a specific thread is still running.
std::uint64_t Id
Handle for a spawned thread; ids start at 1 and are never reused.
void stopAll()
Requests stop on every registered thread's token. Does not wait.
Id spawn(const std::string &name, std::function< void(StopToken)> body)
Starts a new thread running body and registers it. Exceptions escaping the body are logged,...
std::vector< std::string > runningNames() const
Names of the threads that are still running, to show what is holding up a shutdown.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
F_void engineWarn(const F_char *fmt,...)
Log warning for Engine.
std::condition_variable wake
std::shared_ptr< std::atomic< bool > > finished