1#ifndef FRAY_THREAD_MANAGER_HPP
2#define FRAY_THREAD_MANAGER_HPP
6#include <condition_variable>
36 std::condition_variable
wake;
40 std::shared_ptr<State>
_state = std::make_shared<State>();
46 std::lock_guard<std::mutex> lock(
_state->mutex);
55 template<
typename Rep,
typename Period>
57 const std::chrono::duration<Rep, Period>& duration)
const
59 std::unique_lock<std::mutex> lock(
_state->mutex);
60 return _state->wake.wait_for(lock, duration, [
this] {
return _state->stop; });
67 std::lock_guard<std::mutex> lock(
_state->mutex);
86 std::deque<std::function<void()>>
_tasks;
97 std::function<
void()> task)
100 std::lock_guard<std::mutex> lock(
_mutex);
103 _tasks.push_back(std::move(task));
113 std::lock_guard<std::mutex> lock(
_mutex);
125 const std::function<
bool()>& keepAlive =
nullptr)
129 std::function<void()> task;
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(); });
141 task = std::move(
_tasks.front());
148 catch (
const std::exception& error)
170 using Id = std::uint64_t;
205 const std::vector<std::string> remaining =
runningNames();
206 if (!remaining.empty())
209 for (
const std::string& name : remaining)
210 names += (names.empty() ?
"" :
", ") + name;
225 const std::string& name,
229 auto finished = std::make_shared<std::atomic<bool>>(
false);
230 std::thread thread([name, body = std::move(body), token, finished]
236 catch (
const std::exception& error)
244 finished->store(
true);
246 std::lock_guard<std::mutex> lock(
_mutex);
248 _entries.emplace(
id,
Entry{name, std::move(thread), token, finished});
260 std::lock_guard<std::mutex> lock(
_mutex);
261 const auto found =
_entries.find(
id);
262 return found !=
_entries.end() && !found->second.finished->load();
268 std::lock_guard<std::mutex> lock(
_mutex);
269 std::size_t count = 0;
271 if (!entry.second.finished->load())
279 std::lock_guard<std::mutex> lock(
_mutex);
280 std::vector<std::string> names;
282 if (!entry.second.finished->load())
283 names.push_back(entry.second.name);
294 std::lock_guard<std::mutex> lock(
_mutex);
295 const auto found =
_entries.find(
id);
297 found->second.token.requestStop();
311 std::lock_guard<std::mutex> lock(
_mutex);
312 const auto found =
_entries.find(
id);
315 if (found->second.thread.get_id() == std::this_thread::get_id())
317 thread = std::move(found->second.thread);
320 if (thread.joinable())
328 std::lock_guard<std::mutex> lock(
_mutex);
330 entry.second.token.requestStop();
338 std::lock_guard<std::mutex> lock(
_mutex);
340 ids.push_back(entry.first);
342 for (
const Id id : ids)
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