ThreadSchedule 2.0.0
Modern C++ thread management library
Loading...
Searching...
No Matches
threadschedule Namespace Reference

Namespaces

namespace  detail
namespace  profiles

Classes

class  AutoRegisterCurrentThread
 RAII guard that registers the current thread on construction and unregisters it on destruction. More...
class  bad_expected_access
class  BaseThreadWrapper
 Polymorphic base providing common thread management operations. More...
struct  ChaosConfig
 Plain value type holding runtime chaos-testing parameters. More...
class  ChaosController
 RAII controller that periodically perturbs scheduling attributes of registered threads for chaos/fuzz testing. More...
class  CompositeThreadRegistry
 Aggregates multiple ThreadRegistry instances into a single queryable view. More...
struct  CpuTopology
 Snapshot of basic CPU/NUMA topology. More...
class  ErrorHandledTask
 Callable wrapper that catches exceptions and routes them to an ErrorHandler. More...
class  ErrorHandler
 Central registry and dispatcher for task-error callbacks. More...
class  expected
 A result type that holds either a value of type T or an error of type E. More...
class  expected< void, E >
 Specialization of expected for operations that produce no value. More...
class  FutureWithErrorHandler
 A move-only future wrapper that supports an error callback. More...
class  GlobalPool
 Singleton accessor for a process-wide pool instance. More...
class  HighPerformancePool
 High-performance thread pool optimized for high-frequency task submission. More...
struct  IndefiniteWait
 Wait policy that blocks indefinitely until work is available. More...
struct  is_duration_impl
 SFINAE trait that detects std::chrono::duration types. More...
struct  is_duration_impl< T, std::void_t< typename T::rep, typename T::period > >
 SFINAE trait that detects std::chrono::duration types. More...
struct  is_thread_like
 Type trait that identifies thread-like types. More...
struct  is_thread_like< PThreadWrapper >
struct  is_thread_like< std::thread >
 std::thread is a thread-like type. More...
struct  is_thread_like< ThreadWrapper >
struct  is_thread_like< ThreadWrapperView >
class  LightweightPoolT
 Ultra-lightweight fire-and-forget thread pool. More...
struct  PollingWait
 Wait policy that polls with a configurable timeout. More...
class  PoolWithErrors
 Thread pool wrapper that combines any pool type with an ErrorHandler. More...
class  PThreadAttributes
 RAII wrapper for pthread_attr_t with a builder-style API. More...
class  PThreadMutex
 RAII wrapper for pthread_mutex_t. More...
class  PThreadWrapper
 RAII wrapper around POSIX threads with a modern C++ interface. More...
class  PThreadWrapperReg
 PThreadWrapper with automatic registration in the global ThreadRegistry. More...
struct  RegisteredThreadInfo
 Snapshot of metadata for a single registered thread. More...
class  ScheduledTaskHandle
 Copyable handle for a cancellable scheduled task. More...
class  ScheduledThreadPoolT
 Thread pool augmented with delayed and periodic task scheduling. More...
class  SchedulerParams
 Static utility class for constructing OS-native scheduling parameters. More...
struct  TaskError
 Holds diagnostic information captured from a failed task. More...
class  ThreadAffinity
 Manages a set of CPU indices to which a thread may be bound. More...
class  ThreadByNameView
 Looks up an OS thread by its name via /proc and provides scheduling control. More...
class  ThreadControlBlock
 Per-thread control handle for OS-level scheduling operations. More...
class  ThreadInfo
 Static utility class providing hardware and scheduling introspection. More...
class  ThreadPoolBase
 Single-queue thread pool parameterized by its idle-wait strategy. More...
class  ThreadPriority
 Value-semantic wrapper for a thread scheduling priority. More...
struct  ThreadProfile
 Declarative profile bundling scheduling intent for a thread. More...
class  ThreadRegistry
 Central registry of threads indexed by OS-level thread ID (Tid). More...
class  ThreadWrapper
 Owning wrapper around std::thread with RAII join-on-destroy semantics. More...
class  ThreadWrapperReg
 ThreadWrapper with automatic registration in the global ThreadRegistry. More...
class  ThreadWrapperView
 Non-owning view over an externally managed std::thread. More...
struct  unexpect_t
 Tag type used to construct an expected in the error state. More...
class  unexpected
 Exception thrown by expected::value() when the object is in the error state. More...
class  WorkStealingDeque

Typedefs

template<typename T>
using enable_if_thread_callable_t = std::enable_if_t<std::is_invocable_v<T>, int>
 Helper type traits for thread operations.
template<typename T>
using enable_if_duration_t = std::enable_if_t<is_duration_impl<T>::value, int>
using ErrorCallback = std::function<void(TaskError const&)>
 Signature for error-handling callbacks registered with ErrorHandler.
using ScheduledThreadPool = ScheduledThreadPoolT<ThreadPool>
 ScheduledThreadPoolT using the default ThreadPool backend.
using ScheduledHighPerformancePool = ScheduledThreadPoolT<HighPerformancePool>
 ScheduledThreadPoolT using HighPerformancePool as backend.
using ScheduledFastThreadPool = ScheduledThreadPoolT<FastThreadPool>
 ScheduledThreadPoolT using FastThreadPool as backend.
using ScheduledLightweightPool = ScheduledThreadPoolT<LightweightPool>
 ScheduledThreadPoolT using LightweightPool as backend (minimal overhead).
using TaskStartCallback = std::function<void(std::chrono::steady_clock::time_point, std::thread::id)>
 Work-stealing deque for per-thread task queues in a thread pool.
using TaskEndCallback
 Callback invoked when a pool worker finishes executing a task.
using ThreadPool = ThreadPoolBase<IndefiniteWait>
 General-purpose thread pool with indefinite blocking wait.
using FastThreadPool = ThreadPoolBase<PollingWait<>>
 Thread pool with 10 ms polling wait for lower wake-up latency.
using LightweightPool = LightweightPoolT<>
 Default lightweight pool with 64-byte task slots (56 bytes usable).
using GlobalThreadPool = GlobalPool<ThreadPool>
 Singleton accessor for the process-wide ThreadPool instance.
using GlobalHighPerformancePool = GlobalPool<HighPerformancePool>
 Singleton accessor for the process-wide HighPerformancePool instance.
using HighPerformancePoolWithErrors = PoolWithErrors<HighPerformancePool>
 HighPerformancePool with integrated error handling.
using FastThreadPoolWithErrors = PoolWithErrors<FastThreadPool>
 FastThreadPool with integrated error handling.
using ThreadPoolWithErrors = PoolWithErrors<ThreadPool>
 ThreadPool with integrated error handling.
using Tid = pid_t
using JThreadWrapper = ThreadWrapper
 Owning wrapper around std::jthread with cooperative cancellation (C++20).
using JThreadWrapperView = ThreadWrapperView

Enumerations

enum class  SchedulingPolicy : std::uint_fast8_t {
  OTHER = SCHED_OTHER , FIFO = SCHED_FIFO , RR = SCHED_RR , BATCH = SCHED_BATCH ,
  IDLE = SCHED_IDLE
}
 Enumeration of available thread scheduling policies. More...
enum class  ShutdownPolicy : uint8_t { drain , drop_pending }
 Controls how a pool handles pending tasks during shutdown. More...
enum class  BuildMode : std::uint8_t { HEADER_ONLY , RUNTIME }
 Indicates whether the library was compiled in header-only or runtime (shared library) mode. More...

Functions

template<typename Func>
auto make_error_handled_task (Func &&func, std::shared_ptr< ErrorHandler > handler, std::string description="")
 Factory function that creates an ErrorHandledTask with perfect forwarding.
template<typename T, typename E>
constexpr void swap (expected< T, E > &lhs, expected< T, E > &rhs) noexcept(noexcept(lhs.swap(rhs)))
template<typename T>
auto when_all (std::vector< std::future< T > > &futures) -> std::vector< T >
 Block until all futures complete, returning results in submission order.
void when_all (std::vector< std::future< void > > &futures)
 Block until all void futures complete.
template<typename T>
auto when_all_settled (std::vector< std::future< T > > &futures) -> std::vector< expected< T, std::exception_ptr > >
 Block until all futures complete, returning an expected per slot.
auto when_all_settled (std::vector< std::future< void > > &futures) -> std::vector< expected< void, std::exception_ptr > >
 Block until all void futures complete, returning an expected per slot.
template<typename T>
auto when_any (std::vector< std::future< T > > &futures) -> std::pair< size_t, T >
 Block until the first future becomes ready.
auto when_any (std::vector< std::future< void > > &futures) -> size_t
 Block until the first void future becomes ready.
template<typename ThreadLike, std::enable_if_t< is_thread_like_v< ThreadLike >, int > = 0>
auto apply_profile (ThreadLike &t, ThreadProfile const &p) -> expected< void, std::error_code >
 Apply a profile to a thread wrapper or view.
auto apply_profile (ThreadControlBlock &t, ThreadProfile const &p) -> expected< void, std::error_code >
 Apply a profile to a ThreadControlBlock directly.
auto apply_profile (RegisteredThreadInfo &t, ThreadProfile const &p) -> expected< void, std::error_code >
 Apply a profile to a registered thread via its info record.
auto apply_profile (ThreadPool &pool, ThreadProfile const &p) -> expected< void, std::error_code >
 Apply a profile to every worker in a ThreadPool.
auto apply_profile (FastThreadPool &pool, ThreadProfile const &p) -> expected< void, std::error_code >
 Apply a profile to every worker in a FastThreadPool.
auto apply_profile (HighPerformancePool &pool, ThreadProfile const &p) -> expected< void, std::error_code >
 Apply a profile to every worker in a HighPerformancePool.
auto apply_profile (ThreadRegistry &reg, Tid tid, ThreadProfile const &p) -> expected< void, std::error_code >
 Apply a profile to a registry-managed thread identified by TID.
auto to_string (SchedulingPolicy policy) -> std::string
 String conversion utilities.
template<typename Container, typename F>
void parallel_for_each (Container &container, F &&func)
 Convenience wrapper that applies a callable to every element of a container in parallel using the GlobalThreadPool singleton.
auto build_mode () -> BuildMode
 Returns the build mode detected at compile time (header-only variant).
auto build_mode_string () -> char const *
 Returns a human-readable C string describing the active build mode.
auto cgroup_attach_tid (std::string const &cgroupDir, Tid tid) -> expected< void, std::error_code >
 Attaches a thread to a Linux cgroup by writing its TID to the appropriate control file.
auto read_topology () -> CpuTopology
 Discover basic topology. Linux: reads /sys for NUMA nodes. Windows: single node, sequential CPU indices.
auto affinity_for_node (int node_index, int thread_index, int threads_per_node=1) -> ThreadAffinity
 Build a ThreadAffinity for the given NUMA node.
auto distribute_affinities_by_numa (size_t num_threads) -> std::vector< ThreadAffinity >
 Distribute thread affinities across NUMA nodes in round-robin order.
Global registry access

These free functions provide access to a process-wide ThreadRegistry singleton and allow injecting a custom instance.

Header-only mode (default)
Both registry() and set_external_registry() are inline functions that use function-local statics (Meyer's singleton pattern). registry() returns the externally set registry if one was provided via set_external_registry(), otherwise a function-local static instance.
Runtime / shared-library mode (THREADSCHEDULE_RUNTIME defined)
The functions are declared here but defined in runtime_registry.cpp. This ensures a single registry instance across shared-library boundaries even when the header is included from multiple translation units in different DSOs.
auto registry () -> ThreadRegistry &
 Returns a reference to the process-wide ThreadRegistry.
void set_external_registry (ThreadRegistry *reg)
 Injects a custom ThreadRegistry as the global singleton.

Variables

template<typename F, typename... Args>
constexpr bool ThreadCallable = std::is_invocable_v<F, Args...>
 Pre-C++20 fallback for ThreadCallable (constexpr bool).
template<typename T>
constexpr bool ThreadIdentifiable = std::is_same_v<decltype(std::declval<T>().get_id()), std::thread::id>
 Pre-C++20 fallback for ThreadIdentifiable (constexpr bool).
template<typename T>
constexpr bool Duration = is_duration_impl<T>::value
 Pre-C++20 fallback for Duration (constexpr bool).
template<typename T>
constexpr bool PriorityType = std::is_integral_v<T>
 Pre-C++20 fallback for PriorityType (constexpr bool).
template<typename T>
constexpr bool CPUSetType = std::is_same_v<T, std::vector<int>> || std::is_same_v<T, std::set<int>>
 Pre-C++20 fallback for CPUSetType (constexpr bool).
template<typename T>
constexpr bool is_thread_like_v = is_thread_like<T>::value
 Convenience variable template for is_thread_like.
constexpr unexpect_t unexpect {}
constexpr bool is_runtime_build = false
 true when compiled with THREADSCHEDULE_RUNTIME.

Typedef Documentation

◆ enable_if_duration_t

template<typename T>
using threadschedule::enable_if_duration_t = std::enable_if_t<is_duration_impl<T>::value, int>

Definition at line 173 of file concepts.hpp.

◆ enable_if_thread_callable_t

template<typename T>
using threadschedule::enable_if_thread_callable_t = std::enable_if_t<std::is_invocable_v<T>, int>

Helper type traits for thread operations.

Definition at line 170 of file concepts.hpp.

◆ ErrorCallback

using threadschedule::ErrorCallback = std::function<void(TaskError const&)>

Signature for error-handling callbacks registered with ErrorHandler.

Callbacks receive a const reference to the TaskError describing the failure.

Definition at line 116 of file error_handler.hpp.

◆ FastThreadPool

Thread pool with 10 ms polling wait for lower wake-up latency.

Workers poll with condition_variable::wait_for(10 ms), trading a small amount of idle CPU for more consistent latency under bursty workloads.

See also
ThreadPoolBase, PollingWait

Definition at line 1771 of file thread_pool.hpp.

◆ FastThreadPoolWithErrors

FastThreadPool with integrated error handling.

Definition at line 193 of file thread_pool_with_errors.hpp.

◆ GlobalHighPerformancePool

Singleton accessor for the process-wide HighPerformancePool instance.

Definition at line 2265 of file thread_pool.hpp.

◆ GlobalThreadPool

Singleton accessor for the process-wide ThreadPool instance.

Definition at line 2259 of file thread_pool.hpp.

◆ HighPerformancePoolWithErrors

◆ JThreadWrapper

Owning wrapper around std::jthread with cooperative cancellation (C++20).

Analogous to ThreadWrapper but wraps std::jthread, inheriting its built-in cooperative stop semantics. On destruction the underlying std::jthread automatically requests a stop and joins, so the destructor may block until the thread acknowledges the stop request and finishes.

Exposes request_stop(), stop_requested(), get_stop_token(), and get_stop_source() for cooperative cancellation.

Copyability / Movability
  • Not copyable (copy constructor and copy assignment are deleted).
  • Movable. Move assignment transfers ownership directly (the source jthread's destructor handles its own cleanup).
Destruction
Delegates to std::jthread's destructor which calls request_stop() then join(). This will block until the managed thread finishes.
release()
Transfers ownership of the underlying std::jthread out of the wrapper.
create_with_config()
Factory that creates a jthread and attempts to set its name and scheduling policy. Failures from set_name() or set_scheduling_policy() are silently ignored.
Pre-C++20 Fallback
When compiled below C++20, JThreadWrapper is a type alias for ThreadWrapper (which lacks stop-token support).
Thread Safety
Not thread-safe. A single JThreadWrapper must not be mutated concurrently from multiple threads. The stop token/source obtained from the wrapper are independently thread-safe per the standard.

Definition at line 631 of file thread_wrapper.hpp.

◆ JThreadWrapperView

◆ LightweightPool

Default lightweight pool with 64-byte task slots (56 bytes usable).

Sufficient for lambdas capturing up to ~7 pointers on 64-bit platforms.

See also
LightweightPoolT

Definition at line 2116 of file thread_pool.hpp.

◆ ScheduledFastThreadPool

◆ ScheduledHighPerformancePool

◆ ScheduledLightweightPool

◆ ScheduledThreadPool

◆ TaskEndCallback

Initial value:
std::function<void(std::chrono::steady_clock::time_point, std::thread::id, std::chrono::microseconds elapsed)>

Callback invoked when a pool worker finishes executing a task.

Definition at line 323 of file thread_pool.hpp.

◆ TaskStartCallback

using threadschedule::TaskStartCallback = std::function<void(std::chrono::steady_clock::time_point, std::thread::id)>

Work-stealing deque for per-thread task queues in a thread pool.

Implements a double-ended queue where the owning worker thread pushes and pops tasks from the top, while other ("thief") threads steal tasks from the bottom. This asymmetry reduces contention under typical workloads because the owner operates on one end and thieves on the other.

Thread safety
All public operations are serialized by an internal mutex, so the deque is safe to use concurrently from any number of threads. The atomic counters (top_ / bottom_) exist for a fast, lock-free size() / empty() snapshot but do not make push/pop/steal lock-free; the mutex is always acquired.
Capacity
The deque has a fixed capacity set at construction (default DEFAULT_CAPACITY = 1024). push() returns false when the deque is full; it never reallocates. Choose a capacity large enough for your expected burst size or use an overflow queue externally (as HighPerformancePool does).
Memory layout
Each stored item is wrapped in an AlignedItem that is aligned to CACHE_LINE_SIZE (64 bytes) to prevent false sharing between adjacent elements when multiple threads access neighboring slots.
Copyability / movability
Not copyable and not movable (contains a std::mutex).
Template Parameters
TThe task type. Must be move-constructible. Callback invoked when a pool worker begins executing a task.

Definition at line 320 of file thread_pool.hpp.

◆ ThreadPool

General-purpose thread pool with indefinite blocking wait.

Workers block on condition_variable::wait() when idle - zero CPU consumption, instant wake-up on task submission. Suitable for most workloads.

See also
ThreadPoolBase, IndefiniteWait

Definition at line 1760 of file thread_pool.hpp.

◆ ThreadPoolWithErrors

ThreadPool with integrated error handling.

Definition at line 196 of file thread_pool_with_errors.hpp.

◆ Tid

using threadschedule::Tid = pid_t

Definition at line 48 of file thread_registry.hpp.

Enumeration Type Documentation

◆ BuildMode

enum class threadschedule::BuildMode : std::uint8_t
strong

Indicates whether the library was compiled in header-only or runtime (shared library) mode.

The value is determined at compile time by the presence of the THREADSCHEDULE_RUNTIME preprocessor macro.

See also
build_mode(), build_mode_string(), is_runtime_build
Enumerator
HEADER_ONLY 

All symbols are inline / header-only.

RUNTIME 

Core symbols are compiled into a shared library.

Definition at line 735 of file thread_registry.hpp.

◆ SchedulingPolicy

enum class threadschedule::SchedulingPolicy : std::uint_fast8_t
strong

Enumeration of available thread scheduling policies.

Represents the OS-level scheduling policy applied to a thread. On Linux, the enumerator values map directly to the POSIX SCHED_* constants defined in <sched.h>. On Windows, they are stored as portable integer values and translated to Windows-specific priority classes / scheduling behaviour at the point of application.

Linux behaviour

Policy Description Privileges required
OTHER Default CFS (Completely Fair Scheduler) time-sharing. None
FIFO Real-time FIFO - runs until it yields or a higher-priority thread arrives. CAP_SYS_NICE or root
RR Real-time round-robin - like FIFO but with a per-thread time quantum. CAP_SYS_NICE or root
BATCH Like OTHER but the scheduler assumes the thread is CPU-bound (longer slices). None
IDLE Extremely low priority; runs only when no other runnable thread exists. None
DEADLINE EDF (Earliest Deadline First) real-time scheduling (Linux >= 3.14). CAP_SYS_NICE or root

Windows behaviour

Windows does not expose POSIX scheduling policies. The library maps each enumerator to an appropriate combination of process priority class and thread priority level when applying the policy. FIFO and RR are both treated as elevated real-time priorities; BATCH and IDLE are mapped to below-normal and idle priority levels respectively.

Note
DEADLINE is only available on Linux when SCHED_DEADLINE is defined by the kernel headers. It is not available on Windows.
Warning
Setting FIFO, RR, or DEADLINE without adequate privileges will fail with a permission error (EPERM on Linux).
Enumerator
OTHER 

Standard round-robin time-sharing.

FIFO 

First in, first out.

RR 

Round-robin.

BATCH 

For batch style execution.

IDLE 

For very low priority background tasks.

Definition at line 61 of file scheduler_policy.hpp.

◆ ShutdownPolicy

enum class threadschedule::ShutdownPolicy : uint8_t
strong

Controls how a pool handles pending tasks during shutdown.

Passed to shutdown() on any pool type to select graceful vs. immediate shutdown behaviour.

Policy Running tasks Queued tasks
drain Finish Execute, then stop
drop_pending Finish Discard immediately
See also
HighPerformancePool::shutdown, ThreadPoolBase::shutdown, LightweightPoolT::shutdown
Enumerator
drain 

Finish all queued tasks before stopping (default).

drop_pending 

Finish running tasks, discard queued ones.

Definition at line 458 of file thread_pool.hpp.

Function Documentation

◆ affinity_for_node()

auto threadschedule::affinity_for_node ( int node_index,
int thread_index,
int threads_per_node = 1 ) -> ThreadAffinity
inline

Build a ThreadAffinity for the given NUMA node.

Calls read_topology() internally on every invocation (no caching).

Parameters
node_indexNUMA node index (wraps if out of range).
thread_indexUsed to select CPU(s) within the node.
threads_per_nodeNumber of CPUs to include per thread (default 1).

Definition at line 151 of file topology.hpp.

References threadschedule::ThreadAffinity::add_cpu(), threadschedule::CpuTopology::node_to_cpus, threadschedule::CpuTopology::numa_nodes, and read_topology().

Referenced by distribute_affinities_by_numa(), and threadschedule::ChaosController::operator=().

◆ apply_profile() [1/7]

auto threadschedule::apply_profile ( FastThreadPool & pool,
ThreadProfile const & p ) -> expected<void, std::error_code>
inline

Apply a profile to every worker in a FastThreadPool.

Definition at line 192 of file profiles.hpp.

References threadschedule::detail::apply_profile_to_pool().

◆ apply_profile() [2/7]

auto threadschedule::apply_profile ( HighPerformancePool & pool,
ThreadProfile const & p ) -> expected<void, std::error_code>
inline

Apply a profile to every worker in a HighPerformancePool.

Definition at line 200 of file profiles.hpp.

References threadschedule::detail::apply_profile_to_pool().

◆ apply_profile() [3/7]

auto threadschedule::apply_profile ( RegisteredThreadInfo & t,
ThreadProfile const & p ) -> expected<void, std::error_code>
inline

Apply a profile to a registered thread via its info record.

Definition at line 176 of file profiles.hpp.

References apply_profile().

◆ apply_profile() [4/7]

auto threadschedule::apply_profile ( ThreadControlBlock & t,
ThreadProfile const & p ) -> expected<void, std::error_code>
inline

Apply a profile to a ThreadControlBlock directly.

Definition at line 168 of file profiles.hpp.

References threadschedule::detail::apply_profile_to().

◆ apply_profile() [5/7]

template<typename ThreadLike, std::enable_if_t< is_thread_like_v< ThreadLike >, int > = 0>
auto threadschedule::apply_profile ( ThreadLike & t,
ThreadProfile const & p ) -> expected<void, std::error_code>
inline

Apply a profile to a thread wrapper or view.

Template Parameters
ThreadLikeA type satisfying the is_thread_like trait.
Parameters
tThread wrapper or view to configure.
pProfile to apply.
Returns
Empty expected on success, or operation_not_permitted.

Definition at line 160 of file profiles.hpp.

References threadschedule::detail::apply_profile_to().

Referenced by apply_profile().

◆ apply_profile() [6/7]

auto threadschedule::apply_profile ( ThreadPool & pool,
ThreadProfile const & p ) -> expected<void, std::error_code>
inline

Apply a profile to every worker in a ThreadPool.

Definition at line 184 of file profiles.hpp.

References threadschedule::detail::apply_profile_to_pool().

◆ apply_profile() [7/7]

auto threadschedule::apply_profile ( ThreadRegistry & reg,
Tid tid,
ThreadProfile const & p ) -> expected<void, std::error_code>
inline

Apply a profile to a registry-managed thread identified by TID.

Definition at line 208 of file profiles.hpp.

◆ build_mode()

auto threadschedule::build_mode ( ) -> BuildMode
inline

Returns the build mode detected at compile time (header-only variant).

Returns
BuildMode::HEADER_ONLY.

Definition at line 756 of file thread_registry.hpp.

References HEADER_ONLY.

◆ build_mode_string()

auto threadschedule::build_mode_string ( ) -> char const*
inline

Returns a human-readable C string describing the active build mode.

Returns
"runtime" or "header-only".

Definition at line 766 of file thread_registry.hpp.

References is_runtime_build.

◆ cgroup_attach_tid()

auto threadschedule::cgroup_attach_tid ( std::string const & cgroupDir,
Tid tid ) -> expected<void, std::error_code>
inline

Attaches a thread to a Linux cgroup by writing its TID to the appropriate control file.

Tries the following files inside cgroupDir, in order:

  1. cgroup.threads (cgroup v2)
  2. tasks (cgroup v1 / hybrid)
  3. cgroup.procs (cgroup v2 process-level; works for single-threaded workloads)

The first file that can be opened and written to successfully is used.

Parameters
cgroupDirAbsolute path to the target cgroup directory (e.g. "/sys/fs/cgroup/my_group").
tidOS-level thread ID to attach.
Returns
Success, or std::errc::operation_not_permitted if none of the candidate files could be written.
Note
Linux-only. This function is not available on Windows builds.
The calling process needs appropriate permissions (typically CAP_SYS_ADMIN or ownership of the cgroup directory) to write to cgroup control files.

Definition at line 965 of file thread_registry.hpp.

◆ distribute_affinities_by_numa()

auto threadschedule::distribute_affinities_by_numa ( size_t num_threads) -> std::vector<ThreadAffinity>
inline

Distribute thread affinities across NUMA nodes in round-robin order.

Returns one ThreadAffinity per thread, cycling through NUMA nodes so that consecutive threads are spread across different nodes.

Parameters
num_threadsNumber of affinity masks to generate.
Returns
Vector of num_threads ThreadAffinity objects.

Definition at line 182 of file topology.hpp.

References affinity_for_node(), threadschedule::CpuTopology::numa_nodes, and read_topology().

◆ make_error_handled_task()

template<typename Func>
auto threadschedule::make_error_handled_task ( Func && func,
std::shared_ptr< ErrorHandler > handler,
std::string description = "" )

Factory function that creates an ErrorHandledTask with perfect forwarding.

Template Parameters
FuncCallable type (deduced).
Parameters
funcThe callable to wrap.
handlerShared pointer to the ErrorHandler that will receive errors.
descriptionOptional human-readable label stored in TaskError::task_description.
Returns
An ErrorHandledTask<Func> ready to be submitted to a thread pool.

Definition at line 304 of file error_handler.hpp.

◆ parallel_for_each()

template<typename Container, typename F>
void threadschedule::parallel_for_each ( Container & container,
F && func )

Convenience wrapper that applies a callable to every element of a container in parallel using the GlobalThreadPool singleton.

Equivalent to:

GlobalThreadPool::parallel_for_each(container.begin(), container.end(), func);
static void parallel_for_each(Iterator begin, Iterator end, F &&func)

The call blocks until every element has been processed.

Template Parameters
ContainerAny type exposing begin() / end() iterators.
FCallable compatible with void(Container::value_type&).
Parameters
containerThe container whose elements will be processed.
funcThe callable applied to each element.

Definition at line 2285 of file thread_pool.hpp.

References threadschedule::GlobalPool< ThreadPool >::parallel_for_each().

◆ read_topology()

auto threadschedule::read_topology ( ) -> CpuTopology
inline

Discover basic topology. Linux: reads /sys for NUMA nodes. Windows: single node, sequential CPU indices.

Called frequently by chaos/affinity helpers. The result is not cached internally - consider caching the returned CpuTopology yourself if performance of repeated calls matters.

Definition at line 53 of file topology.hpp.

References threadschedule::CpuTopology::cpu_count, threadschedule::CpuTopology::node_to_cpus, and threadschedule::CpuTopology::numa_nodes.

Referenced by affinity_for_node(), distribute_affinities_by_numa(), and threadschedule::ChaosController::operator=().

◆ registry()

auto threadschedule::registry ( ) -> ThreadRegistry&
inline

Returns a reference to the process-wide ThreadRegistry.

If set_external_registry() was called with a non-null pointer, that registry is returned. Otherwise a function-local static instance is used (Meyer's singleton; thread-safe initialisation guaranteed by C++11).

Returns
Reference to the active ThreadRegistry.

Definition at line 694 of file thread_registry.hpp.

Referenced by threadschedule::AutoRegisterCurrentThread::AutoRegisterCurrentThread(), threadschedule::AutoRegisterCurrentThread::operator=(), threadschedule::ChaosController::operator=(), and threadschedule::AutoRegisterCurrentThread::~AutoRegisterCurrentThread().

◆ set_external_registry()

void threadschedule::set_external_registry ( ThreadRegistry * reg)
inline

Injects a custom ThreadRegistry as the global singleton.

After this call, registry() returns reg instead of the default function-local static instance. Pass nullptr to revert to the built-in singleton.

Parameters
regPointer to the registry to use globally. The caller must ensure reg remains valid for the lifetime of all threads that call registry().
Warning
Must be called before any threads are registered if the intent is to capture all threads in a single registry. Calling it after registrations have already occurred leaves those earlier entries in the old (default) registry.

Definition at line 719 of file thread_registry.hpp.

◆ swap()

template<typename T, typename E>
void threadschedule::swap ( expected< T, E > & lhs,
expected< T, E > & rhs )
constexprnoexcept

Definition at line 1035 of file expected.hpp.

◆ to_string()

auto threadschedule::to_string ( SchedulingPolicy policy) -> std::string
inline

String conversion utilities.

Definition at line 469 of file scheduler_policy.hpp.

References BATCH, FIFO, IDLE, OTHER, and RR.

◆ when_all() [1/2]

template<typename T>
auto threadschedule::when_all ( std::vector< std::future< T > > & futures) -> std::vector<T>

Block until all futures complete, returning results in submission order.

If any future throws, the first exception is captured and re-thrown after all remaining futures have been waited on (to avoid leaving them dangling).

Template Parameters
TThe value type of each future.
Parameters
futuresA vector of futures to wait on. Moved-from on return.
Returns
A vector of values in the same order as the input futures.

Definition at line 34 of file futures.hpp.

◆ when_all() [2/2]

void threadschedule::when_all ( std::vector< std::future< void > > & futures)
inline

Block until all void futures complete.

Re-throws the first exception after all futures have been waited on.

Definition at line 65 of file futures.hpp.

◆ when_all_settled() [1/2]

template<typename T>
auto threadschedule::when_all_settled ( std::vector< std::future< T > > & futures) -> std::vector<expected<T, std::exception_ptr>>

Block until all futures complete, returning an expected per slot.

Never throws. Each slot is either the result value or the captured std::exception_ptr.

Template Parameters
TThe value type of each future.

Definition at line 95 of file futures.hpp.

◆ when_all_settled() [2/2]

auto threadschedule::when_all_settled ( std::vector< std::future< void > > & futures) -> std::vector<expected<void, std::exception_ptr>>
inline

Block until all void futures complete, returning an expected per slot.

Definition at line 119 of file futures.hpp.

◆ when_any() [1/2]

template<typename T>
auto threadschedule::when_any ( std::vector< std::future< T > > & futures) -> std::pair<size_t, T>

Block until the first future becomes ready.

Polls all futures round-robin with a 1 ms timeout until one is ready, then returns its index and value.

Note
The remaining futures are left in their current state - the caller is responsible for managing their lifetime.
Template Parameters
TThe value type of each future.
Returns
A pair of (index of the first ready future, its value).

Definition at line 154 of file futures.hpp.

◆ when_any() [2/2]

auto threadschedule::when_any ( std::vector< std::future< void > > & futures) -> size_t
inline

Block until the first void future becomes ready.

Returns
The index of the first ready future.

Definition at line 171 of file futures.hpp.

Variable Documentation

◆ CPUSetType

template<typename T>
bool threadschedule::CPUSetType = std::is_same_v<T, std::vector<int>> || std::is_same_v<T, std::set<int>>
constexpr

Pre-C++20 fallback for CPUSetType (constexpr bool).

Definition at line 123 of file concepts.hpp.

◆ Duration

template<typename T>
bool threadschedule::Duration = is_duration_impl<T>::value
constexpr

Pre-C++20 fallback for Duration (constexpr bool).

Definition at line 115 of file concepts.hpp.

◆ is_runtime_build

bool threadschedule::is_runtime_build = false
inlineconstexpr

true when compiled with THREADSCHEDULE_RUNTIME.

Definition at line 750 of file thread_registry.hpp.

Referenced by build_mode_string().

◆ is_thread_like_v

template<typename T>
bool threadschedule::is_thread_like_v = is_thread_like<T>::value
inlineconstexpr

Convenience variable template for is_thread_like.

Definition at line 164 of file concepts.hpp.

◆ PriorityType

template<typename T>
bool threadschedule::PriorityType = std::is_integral_v<T>
constexpr

Pre-C++20 fallback for PriorityType (constexpr bool).

Definition at line 119 of file concepts.hpp.

◆ ThreadCallable

template<typename F, typename... Args>
bool threadschedule::ThreadCallable = std::is_invocable_v<F, Args...>
constexpr

Pre-C++20 fallback for ThreadCallable (constexpr bool).

See also
ThreadCallable concept above.

Definition at line 107 of file concepts.hpp.

◆ ThreadIdentifiable

template<typename T>
bool threadschedule::ThreadIdentifiable = std::is_same_v<decltype(std::declval<T>().get_id()), std::thread::id>
constexpr

Pre-C++20 fallback for ThreadIdentifiable (constexpr bool).

Definition at line 111 of file concepts.hpp.

◆ unexpect