libstp
Robotics library for Botball
Loading...
Searching...
No Matches
thread_manager.hpp
Go to the documentation of this file.
1#pragma once
2
4
5#include <cstddef>
6#include <cstdint>
7#include <functional>
8#include <mutex>
9#include <string>
10#include <vector>
11
12namespace libstp::threading
13{
14 using DaemonFn = std::function<void(stop_token)>;
15
36 {
37 public:
38 class DaemonHandle;
39
41
45 [[nodiscard]] DaemonHandle add_daemon(std::string name, DaemonFn fn);
46
50 void add_persistent_daemon(std::string name, DaemonFn fn);
51
55 void shutdown();
56
58 [[nodiscard]] std::size_t daemon_count() const;
59
61 ThreadManager(const ThreadManager&) = delete;
63
64 private:
65 friend class DaemonHandle;
66
67 ThreadManager() = default;
68
72 void stop_by_id(std::uint64_t id) noexcept;
73
74 struct Daemon
75 {
76 std::uint64_t id;
77 std::string name;
78 jthread thread;
79 };
80
81 mutable std::mutex mu_;
82 std::vector<Daemon> daemons_;
83 std::uint64_t next_id_ = 1;
84 bool shutdown_ = false;
85 };
86
92 {
93 public:
94 DaemonHandle() noexcept = default;
96
97 DaemonHandle(const DaemonHandle&) = delete;
99
100 DaemonHandle(DaemonHandle&& other) noexcept
101 : mgr_(other.mgr_), id_(other.id_)
102 {
103 other.mgr_ = nullptr;
104 other.id_ = 0;
105 }
106
108 {
109 if (this != &other)
110 {
111 stop();
112 mgr_ = other.mgr_;
113 id_ = other.id_;
114 other.mgr_ = nullptr;
115 other.id_ = 0;
116 }
117 return *this;
118 }
119
122 void stop() noexcept
123 {
124 if (mgr_ != nullptr && id_ != 0)
125 {
126 mgr_->stop_by_id(id_);
127 }
128 mgr_ = nullptr;
129 id_ = 0;
130 }
131
132 [[nodiscard]] bool owns_thread() const noexcept { return mgr_ != nullptr && id_ != 0; }
133
134 private:
135 friend class ThreadManager;
136 DaemonHandle(ThreadManager* mgr, std::uint64_t id) noexcept
137 : mgr_(mgr), id_(id)
138 {
139 }
140
141 ThreadManager* mgr_ = nullptr;
142 std::uint64_t id_ = 0;
143 };
144}
DaemonHandle(const DaemonHandle &)=delete
DaemonHandle & operator=(const DaemonHandle &)=delete
DaemonHandle & operator=(DaemonHandle &&other) noexcept
static ThreadManager & instance()
void add_persistent_daemon(std::string name, DaemonFn fn)
ThreadManager & operator=(const ThreadManager &)=delete
DaemonHandle add_daemon(std::string name, DaemonFn fn)
ThreadManager(const ThreadManager &)=delete
std::size_t daemon_count() const
Number of currently-registered daemons. Test helper.
compat::stop_token stop_token
compat::jthread jthread
std::function< void(stop_token)> DaemonFn