StormByte 3.0.0
C++26 foundation of the StormByte suite
Loading...
Searching...
No Matches
thread.hxx
Go to the documentation of this file.
1/*
2 * Copyright (C) 2024-2026 David C. Manuelda (StormBytePP)
3 *
4 * This is the base for StormByte Suite libraries.
5 *
6 * StormByte original source is dual-licensed:
7 *
8 * 1. GNU Lesser General Public License v3.0 (or later)
9 * You may redistribute and/or modify this file under the terms of the
10 * GNU Lesser General Public License as published by the Free Software
11 * Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * 2. Commercial license
15 * Alternatively, this file may be used under the terms of a commercial
16 * license agreement with the copyright holder
17 * (David C. Manuelda <StormByte@gmail.com>).
18 *
19 * Both licenses apply only to original StormByte source in this repository.
20 * They do not cover other StormByte modules or any third-party material
21 * shipped with this repository (including everything under thirdparty/),
22 * which remains under its own license.
23 *
24 * Neither license grants any patent rights. Any patent licenses required
25 * to use this software or third-party components must be obtained separately
26 * from the patent holders.
27 *
28 * StormByte is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU Lesser General Public License for more details.
32 *
33 * You should have received a copy of the GNU Lesser General Public License
34 * version 3 along with StormByte. If not, see
35 * <https://www.gnu.org/licenses/lgpl-3.0.html>.
36 *
37 * SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-StormByte-Commercial
38 */
39
40#pragma once
41
46
47#include <chrono>
48#include <cstdint>
49#include <functional>
50#include <tuple>
51#include <type_traits>
52#include <utility>
53
58namespace StormByte {
63 namespace Safe {
68 namespace this_thread {}
69
74 namespace Detail {
79 template <class T>
80 struct IsVoidFunction: std::false_type {};
81
86 template <class... Args>
87 struct IsVoidFunction<Function<void(Args...)>>: std::true_type {};
88
96 STORMBYTE_PUBLIC void* ThreadStart(void (*entry)(void*), void* argument);
97
102 STORMBYTE_PUBLIC void ThreadDestroy(void* thread) noexcept;
103
109 STORMBYTE_PUBLIC bool ThreadJoinable(void* thread) noexcept;
110
116 STORMBYTE_PUBLIC void ThreadJoin(void* thread);
117
123 STORMBYTE_PUBLIC void ThreadDetach(void* thread);
124
130 STORMBYTE_PUBLIC std::uint64_t ThreadId(void* thread) noexcept;
131
137 STORMBYTE_PUBLIC std::uintptr_t ThreadNative(void* thread) noexcept;
138
143 STORMBYTE_PUBLIC std::uint64_t ThreadSelf() noexcept;
144
149 STORMBYTE_PUBLIC unsigned ThreadHardware() noexcept;
150
155
160 STORMBYTE_PUBLIC void ThreadSleep(std::uint64_t nanoseconds) noexcept;
161
167 template <class Callable, class... Args>
168 struct ThreadState {
169 Callable callable;
170 std::tuple<Args...> arguments;
171
177 STORMBYTE_FORCE_INLINE ThreadState(Callable&& fn, Args&&... args)
178 : callable(std::move(fn)), arguments(std::move(args)...) {}
179
184 STORMBYTE_FORCE_INLINE static void Run(void* raw) {
185 ThreadState* state = static_cast<ThreadState*>(raw);
186 std::apply(std::move(state->callable), std::move(state->arguments));
187 state->~ThreadState();
188 Heap::Free(raw);
189 }
190 };
191
198 template <class... Args>
200 Function<void(Args...)> function;
201 std::tuple<Args...> arguments;
202
208 STORMBYTE_FORCE_INLINE FunctionState(Function<void(Args...)>&& fn, Args&&... args)
209 : function(std::move(fn)), arguments(std::move(args)...) {}
210
215 STORMBYTE_FORCE_INLINE static void Run(void* raw) {
216 FunctionState* state = static_cast<FunctionState*>(raw);
217 try {
218 std::apply([&state](Args&... args) {
219 (void)state->function.Call(args...);
220 }, state->arguments);
221 }
222 catch (const StormByte::Exception&) {}
223 state->~FunctionState();
224 Heap::Free(raw);
225 }
226 };
227 }
228
238 public:
244 friend class Thread;
245
246 public:
250 inline Id() noexcept
251 : m_value{0} {}
252
258 inline bool operator==(const Id& other) const noexcept {
259 return m_value == other.m_value;
260 }
261
267 inline bool operator!=(const Id& other) const noexcept {
268 return m_value != other.m_value;
269 }
270
276 inline bool operator<(const Id& other) const noexcept {
277 return m_value < other.m_value;
278 }
279
285 inline bool operator<=(const Id& other) const noexcept {
286 return m_value <= other.m_value;
287 }
288
294 inline bool operator>(const Id& other) const noexcept {
295 return m_value > other.m_value;
296 }
297
303 inline bool operator>=(const Id& other) const noexcept {
304 return m_value >= other.m_value;
305 }
306
311 inline std::uint64_t Value() const noexcept {
312 return m_value;
313 }
314
315 private:
320 inline explicit Id(std::uint64_t value) noexcept
321 : m_value{value} {}
322
323 std::uint64_t m_value;
324 };
325
329 using native_handle_type = std::uintptr_t;
330
334 inline Thread() noexcept
335 : m_thread{nullptr} {}
336
345 template <class Callable, class... Args>
346 STORMBYTE_FORCE_INLINE explicit Thread(Callable&& callable, Args&&... args) requires (!Detail::IsVoidFunction<std::decay_t<Callable>>::value)
347 : Thread() {
348 using State = Detail::ThreadState<std::decay_t<Callable>, std::decay_t<Args>...>;
349 void* raw = Heap::Allocate(sizeof(State));
350 State* state = ::new (raw) State(std::forward<Callable>(callable), std::forward<Args>(args)...);
351 m_thread = Detail::ThreadStart(&State::Run, state);
352 }
353
363 template <class... Args>
364 STORMBYTE_FORCE_INLINE explicit Thread(Function<void(Args...)> function, Args&&... args)
365 : Thread() {
367 void* raw = Heap::Allocate(sizeof(State));
368 State* state = ::new (raw) State(std::move(function), std::forward<Args>(args)...);
369 m_thread = Detail::ThreadStart(&State::Run, state);
370 }
371
372 Thread(const Thread&) = delete;
373
378 inline Thread(Thread&& other) noexcept
379 : Thread() {
380 swap(other);
381 }
382
386 inline ~Thread() noexcept {
387 Detail::ThreadDestroy(m_thread);
388 }
389
390 Thread& operator=(const Thread&) = delete;
391
397 inline Thread& operator=(Thread&& other) noexcept {
398 if (this != &other) {
399 Detail::ThreadDestroy(m_thread);
400 m_thread = nullptr;
401 swap(other);
402 }
403 return *this;
404 }
405
410 inline void swap(Thread& other) noexcept {
411 void* mine = m_thread;
412 m_thread = other.m_thread;
413 other.m_thread = mine;
414 }
415
420 inline bool joinable() const noexcept {
421 return m_thread != nullptr && Detail::ThreadJoinable(m_thread);
422 }
423
428 inline void join() {
429 Detail::ThreadJoin(m_thread);
430 }
431
436 inline void detach() {
437 Detail::ThreadDetach(m_thread);
438 }
439
444 inline Id get_id() const noexcept {
445 if (m_thread == nullptr)
446 return Id{};
447 return Id{Detail::ThreadId(m_thread)};
448 }
449
455 if (m_thread == nullptr)
456 return 0;
457 return Detail::ThreadNative(m_thread);
458 }
459
464 inline static unsigned hardware_concurrency() noexcept {
465 return Detail::ThreadHardware();
466 }
467
472 inline static Id Calling() noexcept {
473 return Id{Detail::ThreadSelf()};
474 }
475
476 private:
477 void* m_thread;
478 };
479
485 inline void swap(Thread& left, Thread& right) noexcept {
486 left.swap(right);
487 }
488
489 namespace this_thread {
494 inline Thread::Id get_id() noexcept {
495 return Thread::Calling();
496 }
497
501 inline void yield() noexcept {
503 }
504
511 template <class Rep, class Period>
512 STORMBYTE_FORCE_INLINE void sleep_for(const std::chrono::duration<Rep, Period>& time) noexcept {
513 if (time <= std::chrono::duration<Rep, Period>::zero())
514 return;
515 const auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(time).count();
516 if (nanos <= 0)
517 return;
518 Detail::ThreadSleep(static_cast<std::uint64_t>(nanos));
519 }
520
527 template <class Clock, class Duration>
528 STORMBYTE_FORCE_INLINE void sleep_until(const std::chrono::time_point<Clock, Duration>& time) noexcept {
529 sleep_for(time - Clock::now());
530 }
531 }
532 }
533}
Base exception type for the suite.
Definition exception.hxx:67
Status Call(Args... args) const
Invoke the provider callback.
Definition function.hxx:194
Copyable, creator-context callback with a typed signature.
Definition function.hxx:98
Identifier of an execution.
Definition thread.hxx:243
Id() noexcept
Not an execution.
Definition thread.hxx:250
bool operator<(const Id &other) const noexcept
Order two identifiers.
Definition thread.hxx:276
bool operator!=(const Id &other) const noexcept
Compare two identifiers.
Definition thread.hxx:267
bool operator>=(const Id &other) const noexcept
Order two identifiers.
Definition thread.hxx:303
std::uint64_t Value() const noexcept
Value used by a hash.
Definition thread.hxx:311
friend class Thread
Definition thread.hxx:244
bool operator>(const Id &other) const noexcept
Order two identifiers.
Definition thread.hxx:294
bool operator==(const Id &other) const noexcept
Compare two identifiers.
Definition thread.hxx:258
bool operator<=(const Id &other) const noexcept
Order two identifiers.
Definition thread.hxx:285
Execution owned by Base.
Definition thread.hxx:237
Thread & operator=(const Thread &)=delete
Thread(Thread &&other) noexcept
Take an execution.
Definition thread.hxx:378
~Thread() noexcept
Destroy the handle.
Definition thread.hxx:386
native_handle_type native_handle() noexcept
Native handle as an integer.
Definition thread.hxx:454
static unsigned hardware_concurrency() noexcept
Hint of concurrent executions.
Definition thread.hxx:464
void detach()
Detach the execution.
Definition thread.hxx:436
Thread(const Thread &)=delete
void join()
Wait until the execution returns.
Definition thread.hxx:428
STORMBYTE_FORCE_INLINE Thread(Callable &&callable, Args &&... args)
Start callable in a Base-owned execution.
Definition thread.hxx:346
void swap(Thread &other) noexcept
Exchange two executions.
Definition thread.hxx:410
Thread & operator=(Thread &&other) noexcept
Take an execution.
Definition thread.hxx:397
Thread() noexcept
Not an execution.
Definition thread.hxx:334
static Id Calling() noexcept
Identifier of the calling execution.
Definition thread.hxx:472
bool joinable() const noexcept
Whether this object owns an execution.
Definition thread.hxx:420
std::uintptr_t native_handle_type
Native handle as an integer.
Definition thread.hxx:329
STORMBYTE_FORCE_INLINE Thread(Function< void(Args...)> function, Args &&... args)
Start a void Function in a Base-owned execution.
Definition thread.hxx:364
Id get_id() const noexcept
Identifier of the owned execution.
Definition thread.hxx:444
Private Base heap used by StormByte::Safe::Shared, StormByte::Safe::Unique and StormByte::Safe::Clona...
Private helpers.
void ThreadSleep(std::uint64_t nanoseconds) noexcept
Sleep the calling execution.
std::uintptr_t ThreadNative(void *thread) noexcept
Native handle as an integer.
void ThreadYield() noexcept
Offer the calling execution.
unsigned ThreadHardware() noexcept
Hint of concurrent executions.
std::uint64_t ThreadId(void *thread) noexcept
Identifier of the owned execution.
void ThreadDetach(void *thread)
Detach the execution.
void ThreadDestroy(void *thread) noexcept
Destroy a thread from ThreadStart.
bool ThreadJoinable(void *thread) noexcept
Whether the thread still owns an execution.
void * ThreadStart(void(*entry)(void *), void *argument)
Start a thread whose body lives in Base.
std::uint64_t ThreadSelf() noexcept
Identifier of the calling execution.
void ThreadJoin(void *thread)
Wait until the execution returns.
void * Allocate(std::size_t bytes)
Allocate bytes on Base's heap.
void Free(void *pointer) noexcept
Release a block obtained from Allocate.
Operations on the calling execution.
Thread::Id get_id() noexcept
Identifier of the calling execution.
Definition thread.hxx:494
STORMBYTE_FORCE_INLINE void sleep_for(const std::chrono::duration< Rep, Period > &time) noexcept
Sleep the calling execution.
Definition thread.hxx:512
void yield() noexcept
Offer the calling execution.
Definition thread.hxx:501
STORMBYTE_FORCE_INLINE void sleep_until(const std::chrono::time_point< Clock, Duration > &time) noexcept
Sleep until a time point.
Definition thread.hxx:528
Owned values that cross a DLL without the caller's CRT.
void swap(Binary &left, Binary &right) noexcept
Exchange two sequences.
Definition binary.hxx:760
Root namespace of the StormByte suite.
STL namespace.
#define STORMBYTE_FORCE_INLINE
Definition platform.h:134
Function and its arguments, allocated on Base's heap.
Definition thread.hxx:199
std::tuple< Args... > arguments
Arguments captured before the execution starts.
Definition thread.hxx:201
static STORMBYTE_FORCE_INLINE void Run(void *raw)
Invoke Call and destroy the state.
Definition thread.hxx:215
STORMBYTE_FORCE_INLINE FunctionState(Function< void(Args...)> &&fn, Args &&... args)
Capture the callback and its arguments.
Definition thread.hxx:208
Function< void(Args...)> function
Creator-owned callback.
Definition thread.hxx:200
Whether T is a void-returning Function.
Definition thread.hxx:80
Decayed callable and arguments, allocated on Base's heap.
Definition thread.hxx:168
std::tuple< Args... > arguments
Arguments captured before the execution starts.
Definition thread.hxx:170
static STORMBYTE_FORCE_INLINE void Run(void *raw)
Invoke and destroy the state.
Definition thread.hxx:184
Callable callable
Entry.
Definition thread.hxx:169
STORMBYTE_FORCE_INLINE ThreadState(Callable &&fn, Args &&... args)
Capture the entry.
Definition thread.hxx:177
#define STORMBYTE_PUBLIC
Definition visibility.h:52