GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
Thread.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_SYSTEM_THREAD_HPP
5#define GREM_CORE_SYSTEM_THREAD_HPP
6
8
11#include <GREM/core/time.hpp>
12
13#include <functional> // std::hash
14#include <iosfwd> // std::basic_ostream
15#include <type_traits> // std::is_..._v, std::remove_..._t
16
17#ifdef GREM_USE_MULTITHREADING
18#include <thread> // std::thread, std::this_thread, std::hash<std::thread::id>
19#include <utility> // std::forward
20#elif defined(_WIN32)
21#include <windows.h> // DWORD, Sleep, YieldProcessor
22#elif defined(__linux__)
23#include <cerrno> // errno, EINTR
24#include <sched.h> // sched_yield
25#include <time.h> // nanosleep // NOLINT(modernize-deprecated-headers)
26#endif
27
28#ifndef GREM_USE_MULTITHREADING
30#endif
31
32namespace grem {
33
34namespace detail {
35
36struct InvalidNativeThreadHandle {};
37
38template <typename Thread>
39struct native_thread_handle {
40 using type = InvalidNativeThreadHandle;
41};
42
43template <typename Thread>
44requires(requires { typename Thread::native_handle_type; }) struct native_thread_handle<Thread> {
45 using type = typename Thread::native_handle_type;
46};
47
48} // namespace detail
49
50class Thread; // Forward declaration.
51
52class ThreadID {
53public:
54 [[nodiscard]] GREM_ALWAYS_INLINE static ThreadID getCurrent() noexcept {
55#ifdef GREM_USE_MULTITHREADING
56 return std::this_thread::get_id();
57#else
58 return {};
59#endif
60 }
61
62 ThreadID() noexcept = default;
63
64#ifdef GREM_USE_MULTITHREADING
65 ThreadID(std::thread::id value) noexcept
66 : value(value) {}
67#endif
68
69 [[nodiscard]] bool operator==(const ThreadID&) const = default;
70 [[nodiscard]] auto operator<=>(const ThreadID&) const = default;
71
72 GREM_ALWAYS_INLINE explicit operator bool() const noexcept {
73#ifdef GREM_USE_MULTITHREADING
74 return value != std::thread::id{};
75#else
76 return false;
77#endif
78 }
79
80#ifdef GREM_USE_MULTITHREADING
81 GREM_ALWAYS_INLINE operator std::thread::id() const noexcept {
82 return value;
83 }
84#endif
85
86 template <typename CharT, typename Traits>
87 friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& stream, ThreadID id) {
88#ifdef GREM_USE_MULTITHREADING
89 return stream << id.value;
90#else
91 (void)id;
92 return stream;
93#endif
94 }
95
96private:
97 friend Thread;
98 friend std::hash<ThreadID>;
99
100#ifdef GREM_USE_MULTITHREADING
101 std::thread::id value{};
102#endif
103};
104
105class Thread {
106public:
107#ifdef GREM_USE_MULTITHREADING
108 using native_handle_type = typename detail::native_thread_handle<std::thread>::type;
109#else
110 using native_handle_type = detail::InvalidNativeThreadHandle;
111#endif
112
113 [[nodiscard]] GREM_ALWAYS_INLINE static unsigned int hardware_concurrency() noexcept {
114#ifdef GREM_USE_MULTITHREADING
115 return std::thread::hardware_concurrency();
116#else
117 return 1;
118#endif
119 }
120
121 Thread() noexcept = default;
122 ~Thread() = default;
123
124 template <typename F, typename... Args>
125 GREM_ALWAYS_INLINE Thread([[maybe_unused]] F&& f, [[maybe_unused]] Args&&... args) requires(!std::is_same_v<std::remove_cvref_t<F>, Thread>)
126#ifdef GREM_USE_MULTITHREADING
127 : value(std::forward<F>(f), std::forward<Args>(args)...)
128#endif
129 {
130#ifndef GREM_USE_MULTITHREADING
131 unreachable();
132#endif
133 }
134
135 Thread(Thread&&) noexcept = default;
136 Thread(const Thread&) = delete;
137 Thread& operator=(Thread&&) noexcept = default;
138 Thread& operator=(const Thread&) = delete;
139
140 [[nodiscard]] GREM_ALWAYS_INLINE bool joinable() const noexcept {
141#ifdef GREM_USE_MULTITHREADING
142 return value.joinable();
143#else
144 return false;
145#endif
146 }
147
148 [[nodiscard]] GREM_ALWAYS_INLINE ThreadID get_id() const noexcept {
149#ifdef GREM_USE_MULTITHREADING
150 return value.get_id();
151#else
152 return {};
153#endif
154 }
155
157#ifdef GREM_USE_MULTITHREADING
158 if constexpr (requires { value.native_handle(); }) {
159 return value.native_handle();
160 } else {
161 return {};
162 }
163#else
164 return {};
165#endif
166 }
167
169#ifdef GREM_USE_MULTITHREADING
170 value.join();
171#endif
172 }
173
175#ifdef GREM_USE_MULTITHREADING
176 value.detach();
177#endif
178 }
179
180 GREM_ALWAYS_INLINE void swap([[maybe_unused]] Thread& other) noexcept {
181#ifdef GREM_USE_MULTITHREADING
182 value.swap(other.value);
183#endif
184 }
185
186 GREM_ALWAYS_INLINE friend void swap(Thread& a, Thread& b) noexcept {
187 a.swap(b);
188 }
189
190private:
191#ifdef GREM_USE_MULTITHREADING
192 std::thread value{};
193#endif
194};
195
196GREM_ALWAYS_INLINE void yield() noexcept {
197#ifdef GREM_USE_MULTITHREADING
198 std::this_thread::yield();
199#elif defined(_WIN32)
200 YieldProcessor();
201#elif defined(__linux__)
202 sched_yield();
203#endif
204}
205
206template <typename Rep, typename Period>
208#ifdef GREM_USE_MULTITHREADING
209 std::this_thread::sleep_for(duration);
210#elif defined(_WIN32)
211 if (duration <= DurationBase<Rep, Period>{}) {
212 return;
213 }
214 const TimePoint endTime = Clock::now() + duration_cast<Duration>(duration);
215 using DWORDMilliseconds = DurationBase<DWORD, Ratio<1, 1'000>>;
216 const DWORD milliseconds = floor<DWORDMilliseconds>(duration).count();
217 if (milliseconds > 0) {
218 Sleep(milliseconds);
219 }
220 TimePoint currentTime = Clock::now();
221 while (currentTime < endTime) {
222 currentTime = Clock::now();
223 }
224#elif defined(__linux__)
225 if (duration <= DurationBase<Rep, Period>{}) {
226 return;
227 }
228 struct timespec ts = {};
229 using TimespecSeconds = DurationBase<decltype(ts.tv_sec), Ratio<1, 1>>;
230 using TimespecNanoseconds = DurationBase<decltype(ts.tv_nsec), Ratio<1, 1'000'000'000>>;
231 const TimespecSeconds seconds = floor<TimespecSeconds>(duration);
232 const TimespecNanoseconds nanoseconds = duration_cast<TimespecNanoseconds>(duration - seconds);
233 ts.tv_sec = seconds.count();
234 ts.tv_nsec = nanoseconds.count();
235 struct timespec rem = {};
236 while (nanosleep(&ts, &rem) != 0) {
237 if (errno == EINTR) {
238 ts = rem;
239 rem = {};
240 } else {
241 TimePoint currentTime = Clock::now();
242 const TimePoint endTime = currentTime + duration_cast<Duration>(duration);
243 while (currentTime < endTime) {
244 currentTime = Clock::now();
245 }
246 break;
247 }
248 }
249#else
250 TimePoint currentTime = Clock::now();
251 const TimePoint endTime = currentTime + duration_cast<Duration>(duration);
252 while (currentTime < endTime) {
253 currentTime = Clock::now();
254 }
255#endif
256}
257
258template <typename Clock, typename Duration>
260#ifdef GREM_USE_MULTITHREADING
261 std::this_thread::sleep_until(time);
262#elif defined(_WIN32) || defined(__linux__)
263 typename Clock::time_point currentTime = Clock::now();
264 if constexpr (Clock::is_steady) {
265 if (currentTime < time) {
266 sleepFor(time - currentTime);
267 }
268 } else {
269 while (currentTime < time) {
270 sleepFor(time - currentTime);
271 currentTime = Clock::now();
272 }
273 }
274#else
275 typename Clock::time_point currentTime = Clock::now();
276 while (currentTime < time) {
277 currentTime = Clock::now();
278 }
279#endif
280}
281
282} // namespace grem
283
284template <>
285struct std::hash<grem::ThreadID> {
286 [[nodiscard]] std::size_t operator()(const grem::ThreadID& id) const {
287#ifdef GREM_USE_MULTITHREADING
288 return hasher(id.value);
289#else
290 (void)id;
291 return 0;
292#endif
293 }
294
295#ifdef GREM_USE_MULTITHREADING
296private:
297 std::hash<std::thread::id> hasher;
298#endif
299};
300
301#endif
#define GREM_ALWAYS_INLINE
Definition attributes.hpp:10
Definition Thread.hpp:52
auto operator<=>(const ThreadID &) const =default
friend std::basic_ostream< CharT, Traits > & operator<<(std::basic_ostream< CharT, Traits > &stream, ThreadID id)
Definition Thread.hpp:87
bool operator==(const ThreadID &) const =default
ThreadID() noexcept=default
static GREM_ALWAYS_INLINE ThreadID getCurrent() noexcept
Definition Thread.hpp:54
Definition Thread.hpp:105
GREM_ALWAYS_INLINE friend void swap(Thread &a, Thread &b) noexcept
Definition Thread.hpp:186
GREM_ALWAYS_INLINE void join()
Definition Thread.hpp:168
Thread(Thread &&) noexcept=default
GREM_ALWAYS_INLINE void swap(Thread &other) noexcept
Definition Thread.hpp:180
Thread() noexcept=default
GREM_ALWAYS_INLINE void detach()
Definition Thread.hpp:174
GREM_ALWAYS_INLINE native_handle_type native_handle()
Definition Thread.hpp:156
GREM_ALWAYS_INLINE ThreadID get_id() const noexcept
Definition Thread.hpp:148
static GREM_ALWAYS_INLINE unsigned int hardware_concurrency() noexcept
Definition Thread.hpp:113
detail::InvalidNativeThreadHandle native_handle_type
Definition Thread.hpp:110
GREM_ALWAYS_INLINE bool joinable() const noexcept
Definition Thread.hpp:140
Definition aliases.hpp:9
GREM_ALWAYS_INLINE void sleepFor(const DurationBase< Rep, Period > &duration) noexcept
Definition Thread.hpp:207
GREM_ALWAYS_INLINE constexpr vec< N, T > GREM_VECTORCALL floor(vec< N, T > a)
Definition math.hpp:1421
Clock::time_point TimePoint
Definition Clock.hpp:26
std::ratio< Num, Den > Ratio
Definition time.hpp:19
std::chrono::time_point< Clock, Duration > TimePointBase
Definition time.hpp:42
std::chrono::duration< Rep, Period > DurationBase
Definition time.hpp:39
void unreachable()
Definition assertions.hpp:125
GREM_ALWAYS_INLINE void sleepUntil(const TimePointBase< Clock, Duration > &time) noexcept
Definition Thread.hpp:259
GREM_ALWAYS_INLINE void yield() noexcept
Definition Thread.hpp:196
std::size_t operator()(const grem::ThreadID &id) const
Definition Thread.hpp:286