Thread System 0.3.1
High-performance C++20 thread pool with work stealing and DAG scheduling
Loading...
Searching...
No Matches
kcenon::thread Namespace Reference

Core threading foundation of the thread system library. More...

Namespaces

namespace  adapters
 
namespace  concepts
 
namespace  config
 
namespace  core
 
namespace  detail
 
namespace  diagnostics
 
namespace  impl
 
namespace  interfaces
 
namespace  job_detail
 
namespace  jobs
 
namespace  lockfree
 
namespace  metrics
 
namespace  platform
 
namespace  policies
 
namespace  sync
 
namespace  utility_module
 
namespace  utils
 

Classes

class  adaptive_job_queue
 Adaptive queue that switches between mutex and lock-free modes. More...
 
struct  aged_priority
 Priority with aging support. More...
 
struct  aging_stats
 Statistics about priority aging behavior. More...
 
class  aging_typed_job_queue_t
 A typed job queue with priority aging support, based on policy_queue. More...
 
class  aging_typed_job_t
 A typed job with priority aging support. More...
 
class  atomic_shared_ptr
 
class  atomic_wait_helper
 Helper class to add wait/notify functionality to std::atomic. More...
 
class  atomic_with_wait
 RAII wrapper to add wait/notify to atomic variables. More...
 
class  autoscaler
 Manages automatic scaling of thread pool workers based on load metrics. More...
 
struct  autoscaling_policy
 Configuration for autoscaling behavior. More...
 
class  autoscaling_pool_policy
 Pool policy that implements automatic scaling for dynamic worker management. More...
 
struct  autoscaling_stats
 Statistics for autoscaling operations. More...
 
class  backoff_calculator
 Calculates backoff delays for work-stealing operations. More...
 
struct  backpressure_config
 Configuration for backpressure mechanisms. More...
 
class  backpressure_job_queue
 A job queue with comprehensive backpressure mechanisms. More...
 
struct  backpressure_stats
 Thread-safe statistics for backpressure operations. More...
 
struct  backpressure_stats_snapshot
 Snapshot of backpressure statistics (copyable). More...
 
class  barrier
 C++17-compatible barrier implementation. More...
 
class  callback_job
 A specialized job class that encapsulates user-defined callbacks. More...
 
class  callback_typed_job_t
 Callback-based typed job template. More...
 
class  cancellable_future
 A future wrapper that supports cancellation. More...
 
class  cancellable_future< void >
 Specialization for void return type. More...
 
class  cancellation_callback_guard
 RAII guard for automatic callback unregistration. More...
 
class  cancellation_context
 Thread-local cancellation context for implicit token propagation. More...
 
struct  cancellation_reason
 Holds information about why a cancellation occurred. More...
 
class  cancellation_scope
 Structured cancellation scope with check points. More...
 
class  cancellation_token
 Provides a mechanism for cooperative cancellation of operations. More...
 
class  circuit_breaker_policy
 Pool policy that implements circuit breaker pattern for failure protection. More...
 
class  config_builder
 Builder for thread_system_config. More...
 
struct  config_changed_event
 Configuration changed event. More...
 
class  configuration_manager
 Configuration manager for unified system configuration. More...
 
struct  crash_context
 Crash context information. More...
 
class  crash_handler
 Thread-safe crash handler for the entire thread system. More...
 
struct  dag_config
 Configuration options for the DAG scheduler. More...
 
class  dag_job
 A job with dependency support for DAG-based scheduling. More...
 
class  dag_job_builder
 Fluent builder for creating dag_job instances. More...
 
struct  dag_job_info
 Information about a job in the DAG. More...
 
class  dag_scheduler
 DAG-based job scheduler with dependency management. More...
 
struct  dag_stats
 Statistics about DAG execution. More...
 
class  default_error_handler
 Default error handler implementation. More...
 
class  enhanced_cancellation_token
 Advanced cancellation token with timeout, deadline, and reason support. More...
 
struct  enhanced_work_stealing_config
 Configuration for enhanced work-stealing with NUMA awareness. More...
 
class  error
 Represents an error in the thread system. More...
 
class  error_handler
 Error handler interface. More...
 
class  event_base
 Event base class for type safety. More...
 
class  event_bus
 Event Bus for publish-subscribe pattern. More...
 
class  future_job
 A job that wraps a callable and provides a future for its result. More...
 
struct  has_blocking_overflow
 Compile-time detection of blocking overflow policy. More...
 
struct  has_blocking_overflow< T, std::enable_if_t< policy_queue_traits< T >::is_policy_queue > >
 
class  hazard_pointer
 Single hazard pointer that protects one object from reclamation Uses RAII pattern - automatically releases protection on destruction. More...
 
class  hazard_pointer_domain
 Domain managing hazard pointers and retirement for a specific type. More...
 
struct  is_bounded_queue
 Compile-time detection of bounded queue. More...
 
struct  is_bounded_queue< T, std::enable_if_t< policy_queue_traits< T >::is_policy_queue > >
 
struct  is_lockfree_queue
 Compile-time detection of lock-free capability. More...
 
struct  is_lockfree_queue< T, std::enable_if_t< policy_queue_traits< T >::is_policy_queue > >
 
class  job
 Represents a unit of work (task) to be executed, typically by a job queue. More...
 
class  job_builder
 Fluent builder for creating and configuring jobs with composition. More...
 
struct  job_components
 Internal structure holding composed behaviors for a job. More...
 
struct  job_info
 Information about a job for starvation callback. More...
 
class  job_queue
 A thread-safe job queue for managing and dispatching work items. More...
 
class  job_queue_adapter
 Adapter for job_queue to pool_queue_adapter_interface. More...
 
class  latch
 C++17-compatible latch implementation. More...
 
class  lifecycle_controller
 Centralized thread lifecycle state and synchronization management. More...
 
struct  module_version
 Version information for thread_system module. More...
 
struct  numa_node
 Information about a single NUMA node. More...
 
class  numa_thread_pool
 A NUMA-aware thread pool optimized for Non-Uniform Memory Access architectures. More...
 
class  numa_topology
 NUMA (Non-Uniform Memory Access) topology information. More...
 
class  numa_work_stealer
 NUMA-aware work stealer with enhanced victim selection policies. More...
 
class  operation_cancelled_exception
 Exception thrown when an operation is cancelled. More...
 
struct  performance_alert_event
 Performance alert event. More...
 
class  policy_queue
 Policy-based queue template. More...
 
class  policy_queue_adapter
 Adapter for policy_queue to pool_queue_adapter_interface. More...
 
struct  policy_queue_traits
 Extract policy types from a policy_queue. More...
 
struct  policy_queue_traits< T, std::enable_if_t< detail::has_sync_policy_type< T >::value &&detail::has_bound_policy_type< T >::value &&detail::has_overflow_policy_type< T >::value > >
 
class  pool_future
 A future that can be scheduled on a thread pool. More...
 
class  pool_policy
 Base interface for thread pool policies. More...
 
class  pool_promise
 A promise that can schedule work on a thread pool. More...
 
class  pool_promise< void >
 Specialization for void type. More...
 
class  pool_queue_adapter_interface
 Abstract interface for queue adapters used by thread_pool. More...
 
struct  priority_aging_config
 Configuration for priority aging behavior. More...
 
class  protected_job
 A job wrapper that integrates circuit breaker protection. More...
 
struct  queue_capabilities
 Runtime-queryable queue capabilities descriptor. More...
 
class  queue_capabilities_interface
 Mixin interface for queue capability introspection. More...
 
class  queue_factory
 Factory for creating queue instances. More...
 
struct  queue_type_selector
 Compile-time queue type selector. More...
 
class  result
 A template class representing either a value or an error. More...
 
class  result< void >
 Specialization of result for void. More...
 
class  result_void
 Wrapper for void result. More...
 
class  retry_policy
 Encapsulates retry behavior configuration for jobs. More...
 
class  safe_hazard_guard
 
class  safe_hazard_pointer_domain
 Global Hazard Pointer Domain Manager. More...
 
class  safe_hazard_pointer_record
 Thread-local hazard pointer record with explicit memory ordering. More...
 
struct  scaling_decision
 Scaling decision result. More...
 
struct  scaling_metrics_sample
 Metrics sample for autoscaling decisions. More...
 
class  scheduler_interface
 Scheduler interface for queuing and retrieving jobs. More...
 
class  scoped_crash_callback
 RAII helper for automatic crash callback registration. More...
 
class  scoped_service
 RAII helper for scoped service registration. More...
 
class  service_container
 Modern service container for dependency injection. More...
 
class  service_registry
 Lightweight service registry for dependency lookup. More...
 
struct  steal_backoff_config
 Configuration for backoff behavior. More...
 
struct  submit_options
 Options for submitting jobs to the thread pool. More...
 
struct  system_shutdown_event
 System shutdown event. More...
 
struct  system_startup_event
 System startup event. More...
 
class  thread_base
 A foundational class for implementing custom worker threads. More...
 
class  thread_context
 Context object that provides access to optional services. More...
 
class  thread_context_builder
 Builder for thread_context with fluent interface. More...
 
class  thread_error_category
 std::error_category implementation for thread_system errors More...
 
class  thread_logger
 Structured logger for thread system. More...
 
class  thread_pool
 A thread pool for concurrent execution of jobs using multiple worker threads. More...
 
class  thread_pool_builder
 Fluent builder for creating and configuring thread pools. More...
 
class  thread_pool_crash_safety
 Thread pool crash safety extensions. More...
 
struct  thread_system_config
 Unified configuration for thread_system. More...
 
class  thread_worker
 A specialized worker thread that processes jobs from a job_queue. More...
 
class  token_bucket
 Lock-free token bucket rate limiter for controlling throughput. More...
 
class  typed_job_factory_interface
 Factory interface for creating typed jobs. More...
 
class  typed_job_interface
 Typed job interface template. More...
 
class  typed_job_t
 Typed job template. More...
 
class  typed_safe_hazard_domain
 Typed hazard pointer domain. More...
 
class  typed_thread_pool_builder
 Typed thread pool builder template. More...
 
class  typed_thread_pool_t
 Typed thread pool template. More...
 
class  typed_thread_worker_t
 Typed thread worker template. More...
 
struct  validation_result
 Configuration validation result. More...
 
class  work_affinity_tracker
 Tracks cooperation patterns between workers for locality-aware stealing. More...
 
class  work_stealing_pool_policy
 Pool policy that implements work-stealing behavior for load balancing. More...
 
struct  work_stealing_stats
 Statistics for work-stealing operations. More...
 
struct  work_stealing_stats_snapshot
 Non-atomic snapshot of work-stealing statistics. More...
 
struct  worker_policy
 Worker behavior policy configuration. More...
 

Typedefs

template<typename T >
using result_t = result<T>
 
using standard_queue_adapter
 Adapter for standard_queue (mutex-based, unbounded)
 
using lockfree_queue_adapter
 Adapter for lock-free queue.
 
using config_value
 Configuration value type.
 
using standard_queue
 Standard mutex-based unbounded queue.
 
using policy_lockfree_queue
 Lock-free unbounded queue.
 
using job_id = std::uint64_t
 Unique job identifier for DAG scheduler.
 
using aging_typed_job = aging_typed_job_t<job_types>
 A convenient alias for aging_typed_job_t using the job_types type.
 
using aging_typed_job_queue = aging_typed_job_queue_t<job_types>
 A convenient alias for aging_typed_job_queue_t using the job_types type.
 
using callback_typed_job = callback_typed_job_t<job_types>
 Type alias for a callback_typed_job_t that uses job_types as its priority type.
 
using typed_job = typed_job_t<job_types>
 A convenient alias for typed_job_t using the job_types type.
 
template<detail::JobType job_type>
using typed_job_ptr = std::shared_ptr<typed_job_interface<job_type>>
 Shared pointer type for typed job interfaces.
 
template<detail::JobType job_type>
using typed_job_weak_ptr = std::weak_ptr<typed_job_interface<job_type>>
 Weak pointer type for typed job interfaces.
 
using typed_thread_pool = typed_thread_pool_t<job_types>
 Alias for a typed_thread_pool with the default job_types type.
 
using typed_thread_worker = typed_thread_worker_t<job_types>
 Convenience typedef for a worker configured with default job_types.
 
using crash_callback = std::function<void(const crash_context&)>
 Callback function type for crash handling.
 
using ILogger = common::interfaces::ILogger
 
using IMonitor = common::interfaces::IMonitor
 
template<std::size_t MaxSize>
using bounded_blocking_queue
 Bounded queue with blocking on overflow.
 
template<std::size_t MaxSize>
using bounded_rejecting_queue
 Bounded queue that rejects on overflow.
 
template<std::size_t MaxSize>
using ring_buffer_queue
 Bounded queue that drops oldest on overflow (ring buffer behavior)
 
template<bool NeedExactSize, bool PreferLockFree = false>
using queue_t = typename queue_type_selector<NeedExactSize, PreferLockFree>::type
 Convenience alias for queue type selection.
 
using accurate_queue_t = queue_t<true, false>
 Queue type for accurate size/empty operations (job_queue)
 
using fast_queue_t = queue_t<false, true>
 Queue type for maximum throughput (adaptive_job_queue with performance_first policy)
 
using balanced_queue_t = queue_t<false, false>
 Queue type for balanced performance (adaptive_job_queue)
 

Enumerations

enum class  error_code {
  success = 0 , unknown_error = -101 , operation_canceled = -102 , operation_timeout = -103 ,
  not_implemented = -104 , invalid_argument = -105 , thread_already_running = -110 , thread_not_running = -111 ,
  thread_start_failure = -112 , thread_join_failure = -113 , queue_full = -120 , queue_empty = -121 ,
  queue_stopped = -122 , queue_busy = -123 , job_creation_failed = -130 , job_execution_failed = -131 ,
  job_invalid = -132 , resource_allocation_failed = -140 , resource_limit_reached = -141 , mutex_error = -150 ,
  deadlock_detected = -151 , condition_variable_error = -152 , io_error = -160 , file_not_found = -161 ,
  success = 0 , unknown_error = -101 , operation_canceled = -102 , operation_timeout = -103 ,
  not_implemented = -104 , invalid_argument = -105 , thread_already_running = -110 , thread_not_running = -111 ,
  thread_start_failure = -112 , thread_join_failure = -113 , queue_full = -120 , queue_empty = -121 ,
  queue_stopped = -122 , queue_busy = -123 , job_creation_failed = -130 , job_execution_failed = -131 ,
  job_invalid = -132 , resource_allocation_failed = -140 , resource_limit_reached = -141 , mutex_error = -150 ,
  deadlock_detected = -151 , condition_variable_error = -152 , io_error = -160 , file_not_found = -161 ,
  circuit_open = -170 , circuit_half_open = -171
}
 Strongly typed error codes for thread system operations. More...
 
enum class  backpressure_policy {
  backpressure_policy::block , backpressure_policy::drop_oldest , backpressure_policy::drop_newest , backpressure_policy::callback ,
  backpressure_policy::adaptive
}
 Policy for handling queue overflow conditions. More...
 
enum class  backpressure_decision { backpressure_decision::accept , backpressure_decision::reject , backpressure_decision::drop_and_accept , backpressure_decision::delay }
 Decision returned by callback policy handler. More...
 
enum class  pressure_level { pressure_level::none , pressure_level::low , pressure_level::high , pressure_level::critical }
 Current pressure level for graduated response. More...
 
enum class  error_code {
  success = 0 , unknown_error = -101 , operation_canceled = -102 , operation_timeout = -103 ,
  not_implemented = -104 , invalid_argument = -105 , thread_already_running = -110 , thread_not_running = -111 ,
  thread_start_failure = -112 , thread_join_failure = -113 , queue_full = -120 , queue_empty = -121 ,
  queue_stopped = -122 , queue_busy = -123 , job_creation_failed = -130 , job_execution_failed = -131 ,
  job_invalid = -132 , resource_allocation_failed = -140 , resource_limit_reached = -141 , mutex_error = -150 ,
  deadlock_detected = -151 , condition_variable_error = -152 , io_error = -160 , file_not_found = -161 ,
  success = 0 , unknown_error = -101 , operation_canceled = -102 , operation_timeout = -103 ,
  not_implemented = -104 , invalid_argument = -105 , thread_already_running = -110 , thread_not_running = -111 ,
  thread_start_failure = -112 , thread_join_failure = -113 , queue_full = -120 , queue_empty = -121 ,
  queue_stopped = -122 , queue_busy = -123 , job_creation_failed = -130 , job_execution_failed = -131 ,
  job_invalid = -132 , resource_allocation_failed = -140 , resource_limit_reached = -141 , mutex_error = -150 ,
  deadlock_detected = -151 , condition_variable_error = -152 , io_error = -160 , file_not_found = -161 ,
  circuit_open = -170 , circuit_half_open = -171
}
 
enum class  job_priority {
  lowest = 0 , low = 1 , normal = 2 , high = 3 ,
  highest = 4 , realtime = 5
}
 Priority levels for job scheduling. More...
 
enum class  log_level_v2 : uint8_t {
  trace = 0 , debug = 1 , info = 2 , warn = 3 ,
  error = 4 , critical = 5 , off = 6
}
 Logging severity levels with explicit ascending values. More...
 
enum class  retry_strategy { none , fixed , linear , exponential_backoff }
 Defines the strategy for calculating delay between retry attempts. More...
 
enum class  thread_conditions : uint8_t {
  Created , Waiting , Working , Stopping ,
  Stopped
}
 Enumeration of various states in a thread's lifecycle. More...
 
enum class  log_level {
  trace , debug , info , warning ,
  error , critical
}
 Logging severity levels (legacy). More...
 
enum class  worker_state {
  created , starting , active , idle ,
  stopping , stopped
}
 Enumeration of worker states. More...
 
enum class  scheduling_policy { fifo , lifo , priority , work_stealing }
 Enumeration of scheduling policies. More...
 
enum class  steal_policy { random , round_robin , adaptive }
 Policy for selecting steal victims. More...
 
enum class  dag_failure_policy { fail_fast , continue_others , retry , fallback }
 Defines how the DAG scheduler handles job failures. More...
 
enum class  dag_job_state {
  pending , ready , running , completed ,
  failed , cancelled , skipped
}
 State of a job in the DAG scheduler. More...
 
enum class  job_types : uint8_t { RealTime , Batch , Background }
 Defines different types of jobs for a typed thread pool. More...
 
enum class  aging_curve : uint8_t { linear , exponential , logarithmic }
 Defines different aging curve algorithms. More...
 
enum class  crash_safety_level { minimal , standard , paranoid }
 Crash safety levels for different scenarios. More...
 
enum class  scaling_direction { none , up , down }
 Scaling direction for autoscaling decisions. More...
 
enum class  scaling_reason {
  queue_depth , worker_utilization , latency , manual ,
  scheduled
}
 Reason for scaling decision. More...
 
enum class  enhanced_steal_policy : std::uint8_t {
  random , round_robin , adaptive , numa_aware ,
  locality_aware , hierarchical
}
 Enhanced policies for selecting work-stealing victims. More...
 
enum class  steal_backoff_strategy : std::uint8_t { fixed , linear , exponential , adaptive_jitter }
 Backoff strategies for work-stealing operations. More...
 

Functions

std::string error_code_to_string (error_code code)
 Converts an error_code to a string representation.
 
template<typename T >
result< T > optional_error_to_result (const std::optional< std::string > &error, T &&value)
 
result< void > optional_error_to_result (const std::optional< std::string > &error)
 
std::optional< std::string > result_to_optional_error (const result< void > &res)
 
template<typename T >
std::pair< std::optional< T >, std::optional< std::string > > result_to_pair (const result< T > &res)
 
template<typename PolicyQueueType >
auto make_policy_queue_adapter () -> std::unique_ptr< pool_queue_adapter_interface >
 Create a pool_queue_adapter from a policy_queue type.
 
template<typename PolicyQueueType >
auto make_policy_queue_adapter (typename PolicyQueueType::bound_policy_type bound_policy) -> std::unique_ptr< pool_queue_adapter_interface >
 Create a pool_queue_adapter with bound policy.
 
auto make_standard_queue_adapter () -> std::unique_ptr< pool_queue_adapter_interface >
 Create a standard_queue adapter.
 
auto make_lockfree_queue_adapter () -> std::unique_ptr< pool_queue_adapter_interface >
 Create a lock-free queue adapter.
 
template<typename T , typename... Args>
atomic_shared_ptr< T > make_atomic_shared (Args &&... args)
 Make an atomic_shared_ptr with a new object.
 
auto pressure_level_to_string (pressure_level level) -> std::string
 Converts pressure_level to human-readable string.
 
auto backpressure_policy_to_string (backpressure_policy policy) -> std::string
 Converts backpressure_policy to human-readable string.
 
common::error_info to_error_info (error_code code, const std::string &message="")
 Convert a thread::error_code to common::error_info.
 
common::VoidResult make_error_result (error_code code, const std::string &message="")
 Create a common::VoidResult error from a thread::error_code.
 
template<typename T >
common::Result< T > make_error_result (error_code code, const std::string &message="")
 Create a common::Result<T> error from a thread::error_code.
 
error_code get_error_code (const common::error_info &info)
 Extract thread::error_code from a common::error_info.
 
const std::error_category & thread_category () noexcept
 Gets the singleton instance of thread_error_category.
 
std::error_code make_error_code (error_code e) noexcept
 Creates a std::error_code from a thread_system error_code.
 
std::error_condition make_error_condition (error_code e) noexcept
 Creates a std::error_condition from a thread_system error_code.
 
template<typename T >
pool_future< std::decay_t< T > > make_ready_future (T &&value)
 Create a future that is already ready with a value.
 
pool_future< void > make_ready_future ()
 Create a future that is already ready with void.
 
template<typename T >
pool_future< T > make_exceptional_future (std::exception_ptr exception)
 Create a future that is already ready with an exception.
 
template<typename... Futures>
void wait_for_all (Futures &... futures)
 Wait for all futures to complete.
 
template<typename... Futures>
size_t wait_for_any (Futures &... futures)
 Wait for any future to complete.
 
auto make_job () -> job_builder
 
constexpr std::string_view to_string (log_level_v2 level) noexcept
 Convert log_level_v2 to string representation.
 
constexpr bool should_log (log_level_v2 message_level, log_level_v2 min_level) noexcept
 Check if a log level should be logged given a minimum level.
 
log_level_v2 parse_log_level (std::string_view str) noexcept
 Parse string to log_level_v2.
 
template<typename T >
void safe_retire_hazard (T *p)
 
constexpr std::string_view to_string (thread_conditions condition)
 Converts a thread_conditions value to its corresponding string representation.
 
auto get_all_thread_conditions (void) -> std::vector< thread_conditions >
 Retrieves a vector containing all possible thread_conditions values.
 
constexpr const char * to_string (worker_state state)
 Convert worker state to string representation.
 
constexpr const char * to_string (scheduling_policy policy)
 Convert scheduling policy to string representation.
 
constexpr const char * to_string (steal_policy policy)
 Convert steal policy to string representation.
 
auto dag_failure_policy_to_string (dag_failure_policy policy) -> std::string
 Convert dag_failure_policy to string representation.
 
auto dag_job_state_to_string (dag_job_state state) -> std::string
 Convert dag_job_state to string representation.
 
constexpr std::string_view to_string (job_types job_type)
 Converts a job_types value to its corresponding string representation.
 
auto get_all_job_types (void) -> std::vector< job_types >
 Returns a vector containing all possible job_types values.
 
template<detail::JobType job_type = job_types>
typed_thread_pool_builder< job_type > create_pool_builder ()
 Convenience function to create a builder.
 
constexpr const char * to_string (enhanced_steal_policy policy)
 Convert enhanced_steal_policy to string representation.
 
constexpr const char * to_string (steal_backoff_strategy strategy)
 Convert steal_backoff_strategy to string representation.
 
template<typename... Futures>
auto when_all (Futures &&... futures) -> std::future< std::tuple< detail::future_value_type_t< std::decay_t< Futures > >... > >
 Wait for all futures to complete and return their results as a tuple.
 
auto when_all_empty () -> std::future< std::tuple<> >
 Overload of when_all for no arguments.
 
template<typename T >
auto when_any (std::vector< std::future< T > > &&futures) -> std::future< T >
 Wait for any future to complete and return its result.
 
auto when_any (std::vector< std::future< void > > &&futures) -> std::future< void >
 Specialization of when_any for void futures.
 
template<typename T >
auto when_any_with_index (std::vector< std::future< T > > &&futures) -> std::future< std::pair< std::size_t, T > >
 Wait for any future to complete with index.
 

Variables

constexpr job_id INVALID_JOB_ID = 0
 Invalid job ID constant.
 
template<typename T >
constexpr bool is_sync_policy_v = detail::has_sync_policy_tag<T>::value
 Check if type is a sync policy.
 
template<typename T >
constexpr bool is_bound_policy_v = detail::has_bound_policy_tag<T>::value
 Check if type is a bound policy.
 
template<typename T >
constexpr bool is_overflow_policy_v = detail::has_overflow_policy_tag<T>::value
 Check if type is an overflow policy.
 
template<typename T >
constexpr bool is_policy_queue_v = detail::is_policy_queue_impl<std::remove_cv_t<T>>::value
 Check if type is a policy_queue instantiation.
 
template<typename T >
constexpr bool is_scheduler_v = std::is_base_of_v<scheduler_interface, std::remove_cv_t<T>>
 Check if type is a scheduler_interface.
 
template<typename T >
constexpr bool is_queue_capabilities_v
 Check if type is a queue_capabilities_interface.
 
template<typename T >
constexpr bool is_lockfree_queue_v = is_lockfree_queue<T>::value
 
template<typename T >
constexpr bool is_bounded_queue_v = is_bounded_queue<T>::value
 
template<typename T >
constexpr bool has_blocking_overflow_v = has_blocking_overflow<T>::value
 

Detailed Description

Core threading foundation of the thread system library.

Type-based thread pool implementation for job scheduling with types.

Thread pool implementation for managing worker threads.

Deprecated
This header is deprecated. Use thread_config.h instead.

For unified configuration, include:

.enable_backpressure()
.with_backpressure_policy(backpressure_policy::adaptive)
.build();
@ adaptive
Automatically adjust based on load conditions.
static auto builder() -> config_builder
Creates a builder for fluent configuration.
Public facade for thread_system configuration.

The thread_module namespace provides fundamental threading primitives including the base thread class, jobs, job queues, and synchronization utilities. It serves as the foundation for all thread-related functionality in the library.

Key components include:

  • thread_base: The fundamental worker thread class
  • job: The base unit of work that can be scheduled and executed
  • job_queue: A thread-safe queue for storing and retrieving jobs
  • cancellation_token: Mechanism for cancelling ongoing operations

This namespace implements low-level threading concepts while higher-level functionality like thread pools are implemented in separate namespaces that build upon these primitives.

The thread_pool_module namespace provides a standard thread pool implementation for processing jobs concurrently using a team of worker threads.

Key components include:

  • thread_pool: The primary thread pool class managing multiple workers and a shared job queue
  • thread_worker: A specialized worker thread that processes jobs from a shared queue
  • task: A template-based convenience wrapper for creating and submitting callable jobs

The thread pool pattern improves performance by:

  • Reusing threads rather than creating new ones for each task
  • Reducing thread creation overhead
  • Limiting the total number of threads to control resource usage
  • Providing a simple interface for async task execution
See also
kcenon::thread for a more advanced implementation with job prioritization
Deprecated
This header is deprecated. Use thread_config.h instead.

For unified configuration, include:

.with_dag_failure_policy(dag_failure_policy::retry)
.with_dag_retry_params(3, std::chrono::seconds{1})
.build();
@ retry
Retry failed job (with max retries)
Deprecated
This header is deprecated. Use thread_config.h instead.

For unified configuration, include:

.enable_priority_aging()
.with_priority_aging_params(std::chrono::seconds{1}, 1, 3)
.build();

The kcenon::thread namespace extends the basic thread pool concept with priority-based scheduling of jobs. It allows jobs to be processed according to their importance or urgency rather than just their order of submission.

Key components include:

This implementation allows for:

  • Custom priority types through template parameters
  • RealTimeer priority jobs being processed ahead of lower priority ones
  • Dynamic adjustment of types based on application needs
See also
thread_pool_module for the basic non-prioritized implementation

Typedef Documentation

◆ accurate_queue_t

Queue type for accurate size/empty operations (job_queue)

Definition at line 320 of file queue_factory.h.

◆ aging_typed_job

A convenient alias for aging_typed_job_t using the job_types type.

Definition at line 171 of file aging_typed_job.h.

◆ aging_typed_job_queue

A convenient alias for aging_typed_job_queue_t using the job_types type.

Definition at line 404 of file aging_typed_job_queue.h.

◆ balanced_queue_t

Queue type for balanced performance (adaptive_job_queue)

Definition at line 327 of file queue_factory.h.

◆ bounded_blocking_queue

template<std::size_t MaxSize>
using kcenon::thread::bounded_blocking_queue
Initial value:
policy_queue<
policies::mutex_sync_policy,
policies::bounded_policy,
policies::overflow_block_policy
>

Bounded queue with blocking on overflow.

Definition at line 404 of file policy_queue.h.

◆ bounded_rejecting_queue

template<std::size_t MaxSize>
using kcenon::thread::bounded_rejecting_queue
Initial value:
policy_queue<
policies::mutex_sync_policy,
policies::bounded_policy,
policies::overflow_reject_policy
>

Bounded queue that rejects on overflow.

Definition at line 414 of file policy_queue.h.

◆ callback_typed_job

Type alias for a callback_typed_job_t that uses job_types as its priority type.

Definition at line 95 of file callback_typed_job.h.

◆ config_value

Initial value:
std::variant<
bool,
int,
double,
std::string,
std::vector<std::string>,
std::unordered_map<std::string, std::any>
>

Configuration value type.

Definition at line 31 of file configuration_manager.h.

◆ crash_callback

using kcenon::thread::crash_callback = std::function<void(const crash_context&)>

Callback function type for crash handling.

Definition at line 50 of file crash_handler.h.

◆ fast_queue_t

using kcenon::thread::fast_queue_t = queue_t<false, true>

Queue type for maximum throughput (adaptive_job_queue with performance_first policy)

Note
lockfree_job_queue is now an internal implementation detail

Definition at line 324 of file queue_factory.h.

◆ ILogger

using kcenon::thread::ILogger = common::interfaces::ILogger

Definition at line 25 of file thread_context.h.

◆ IMonitor

using kcenon::thread::IMonitor = common::interfaces::IMonitor

Definition at line 28 of file thread_context.h.

◆ job_id

using kcenon::thread::job_id = std::uint64_t

Unique job identifier for DAG scheduler.

Definition at line 33 of file dag_job.h.

◆ lockfree_queue_adapter

Initial value:
policy_queue_adapter<
policies::lockfree_sync_policy,
policies::unbounded_policy,
policies::overflow_reject_policy
>

Adapter for lock-free queue.

Definition at line 205 of file policy_queue_adapter.h.

◆ policy_lockfree_queue

Initial value:
policy_queue<
policies::lockfree_sync_policy,
policies::unbounded_policy,
policies::overflow_reject_policy
>

Lock-free unbounded queue.

Note
Named policy_lockfree_queue to avoid collision with the deprecated template lockfree_queue<T> in forward.h
Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/thread_pool.h.

Definition at line 95 of file thread_pool.h.

◆ queue_t

template<bool NeedExactSize, bool PreferLockFree = false>
using kcenon::thread::queue_t = typename queue_type_selector<NeedExactSize, PreferLockFree>::type

Convenience alias for queue type selection.

Template Parameters
NeedExactSizeIf true, selects job_queue
PreferLockFreeIf true and NeedExactSize is false, selects lockfree_job_queue

Definition at line 313 of file queue_factory.h.

◆ result_t

template<typename T >
using kcenon::thread::result_t = result<T>

Definition at line 605 of file error_handling.h.

◆ ring_buffer_queue

template<std::size_t MaxSize>
using kcenon::thread::ring_buffer_queue
Initial value:
policy_queue<
policies::mutex_sync_policy,
policies::bounded_policy,
policies::overflow_drop_oldest_policy
>

Bounded queue that drops oldest on overflow (ring buffer behavior)

Definition at line 424 of file policy_queue.h.

◆ standard_queue

Initial value:
policy_queue<
policies::mutex_sync_policy,
policies::unbounded_policy,
policies::overflow_reject_policy
>

Standard mutex-based unbounded queue.

Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/thread_pool.h.

Definition at line 89 of file thread_pool.h.

◆ standard_queue_adapter

Initial value:
policy_queue_adapter<
policies::mutex_sync_policy,
policies::unbounded_policy,
policies::overflow_reject_policy
>

Adapter for standard_queue (mutex-based, unbounded)

Definition at line 196 of file policy_queue_adapter.h.

◆ typed_job

A convenient alias for typed_job_t using the job_types type.

Definition at line 68 of file typed_job.h.

◆ typed_job_ptr

template<detail::JobType job_type>
using kcenon::thread::typed_job_ptr = std::shared_ptr<typed_job_interface<job_type>>

Shared pointer type for typed job interfaces.

Definition at line 99 of file typed_job_interface.h.

◆ typed_job_weak_ptr

template<detail::JobType job_type>
using kcenon::thread::typed_job_weak_ptr = std::weak_ptr<typed_job_interface<job_type>>

Weak pointer type for typed job interfaces.

Definition at line 105 of file typed_job_interface.h.

◆ typed_thread_pool

Alias for a typed_thread_pool with the default job_types type.

Definition at line 470 of file typed_thread_pool.h.

◆ typed_thread_worker

Convenience typedef for a worker configured with default job_types.

Definition at line 212 of file typed_thread_worker.h.

Enumeration Type Documentation

◆ aging_curve

enum class kcenon::thread::aging_curve : uint8_t
strong

Defines different aging curve algorithms.

The aging curve determines how priority boost is calculated over time.

Enumerator
linear 

Constant boost per interval.

exponential 

Increasing boost over time.

logarithmic 

Decreasing boost (fast initial, slow later)

Definition at line 52 of file priority_aging_config.h.

53 {
54 linear,
57 };
@ linear
Linearly increasing delay.
@ logarithmic
Decreasing boost (fast initial, slow later)
@ exponential
Increasing boost over time.

◆ crash_safety_level

Crash safety levels for different scenarios.

Enumerator
minimal 
standard 
paranoid 

Definition at line 29 of file crash_handler.h.

29 {
30 minimal, // Basic signal handling
31 standard, // Standard recovery with logging
32 paranoid // Maximum safety with redundancy
33};

◆ dag_failure_policy

Defines how the DAG scheduler handles job failures.

Enumerator
fail_fast 

Cancel all dependents immediately on failure.

continue_others 

Continue unrelated jobs, skip dependents.

retry 

Retry failed job (with max retries)

fallback 

Execute fallback job if available.

Definition at line 41 of file dag_config.h.

42 {
43 fail_fast,
45 retry,
47 };
@ fallback
Execute fallback job if available.
@ continue_others
Continue unrelated jobs, skip dependents.
@ fail_fast
Cancel all dependents immediately on failure.

◆ dag_job_state

enum class kcenon::thread::dag_job_state
strong

State of a job in the DAG scheduler.

Enumerator
pending 

Waiting for dependencies to complete.

ready 

Dependencies satisfied, can be executed.

running 

Currently executing.

completed 

Successfully completed.

failed 

Execution failed.

cancelled 

Cancelled by user or dependency failure.

skipped 

Skipped due to dependency failure.

Definition at line 44 of file dag_job.h.

45 {
46 pending,
47 ready,
48 running,
49 completed,
50 failed,
51 cancelled,
52 skipped
53 };
@ ready
Dependencies satisfied, can be executed.
@ skipped
Skipped due to dependency failure.

◆ enhanced_steal_policy

enum class kcenon::thread::enhanced_steal_policy : std::uint8_t
strong

Enhanced policies for selecting work-stealing victims.

These policies extend the basic steal_policy with NUMA awareness and locality optimizations. Choose based on your workload characteristics and system architecture.

Policy Comparison

Policy Description Best For
random Random victim selection General use, good load distribution
round_robin Sequential selection Deterministic, fair distribution
adaptive Queue size based Uneven workloads
numa_aware Prefer same NUMA node NUMA systems with memory locality
locality_aware Prefer recently cooperated Cache-sensitive workloads
hierarchical NUMA node -> random Large NUMA systems
Enumerator
random 

Random victim selection (baseline, good distribution)

round_robin 

Sequential victim selection (deterministic, fair)

adaptive 

Select based on queue sizes (best for uneven loads)

numa_aware 

Prefer workers on the same NUMA node (reduces cross-node traffic)

locality_aware 

Prefer workers with recent cooperation history (cache affinity)

hierarchical 

NUMA node first, then random within node (large NUMA systems)

Definition at line 37 of file enhanced_steal_policy.h.

38{
39 random,
41 adaptive,
45};
@ round_robin
Sequential victim selection (deterministic, fair)
@ random
Random victim selection (default, good load distribution)
@ hierarchical
NUMA node first, then random within node (large NUMA systems)
@ locality_aware
Prefer workers with recent cooperation history (cache affinity)
@ numa_aware
Prefer workers on the same NUMA node (reduces cross-node traffic)

◆ error_code [1/2]

enum class kcenon::thread::error_code
strong

Strongly typed error codes for thread system operations.

Error codes are in the range [-199, -100] to comply with the central error code registry in common_system. The range is organized as:

  • General errors: -100 to -109
  • Thread errors: -110 to -119
  • Queue errors: -120 to -129
  • Job errors: -130 to -139
  • Resource errors: -140 to -149
  • Synchronization errors: -150 to -159
  • IO errors: -160 to -169

These error codes are specific to thread_system operations and can be converted to common::error_info for use with common::Result<T> and common::VoidResult.

Error codes are in the range [-199, -100] to comply with the central error code registry in common_system. The range is organized as:

  • General errors: -100 to -109
  • Thread errors: -110 to -119
  • Queue errors: -120 to -129
  • Job errors: -130 to -139
  • Resource errors: -140 to -149
  • Synchronization errors: -150 to -159
  • IO errors: -160 to -169
Enumerator
success 
unknown_error 
operation_canceled 
operation_timeout 
not_implemented 
invalid_argument 
thread_already_running 
thread_not_running 
thread_start_failure 
thread_join_failure 
queue_full 
queue_empty 
queue_stopped 
queue_busy 
job_creation_failed 
job_execution_failed 
job_invalid 
resource_allocation_failed 
resource_limit_reached 
mutex_error 
deadlock_detected 
condition_variable_error 
io_error 
file_not_found 
success 
unknown_error 
operation_canceled 
operation_timeout 
not_implemented 
invalid_argument 
thread_already_running 
thread_not_running 
thread_start_failure 
thread_join_failure 
queue_full 
queue_empty 
queue_stopped 
queue_busy 
job_creation_failed 
job_execution_failed 
job_invalid 
resource_allocation_failed 
resource_limit_reached 
mutex_error 
deadlock_detected 
condition_variable_error 
io_error 
file_not_found 
circuit_open 

Circuit breaker is open, request rejected.

circuit_half_open 

Circuit breaker is in half-open state.

Definition at line 39 of file error_handling.h.

39 {
40 // General errors (-100 to -109)
41 success = 0,
42 unknown_error = -101,
43 operation_canceled = -102,
44 operation_timeout = -103,
45 not_implemented = -104,
46 invalid_argument = -105,
47
48 // Thread errors (-110 to -119)
50 thread_not_running = -111,
53
54 // Queue errors (-120 to -129)
55 queue_full = -120,
56 queue_empty = -121,
57 queue_stopped = -122,
58 queue_busy = -123, // Queue is temporarily busy with concurrent operations
59
60 // Job errors (-130 to -139)
63 job_invalid = -132,
64
65 // Resource errors (-140 to -149)
68
69 // Synchronization errors (-150 to -159)
70 mutex_error = -150,
71 deadlock_detected = -151,
73
74 // IO errors (-160 to -169)
75 io_error = -160,
76 file_not_found = -161
77};

◆ error_code [2/2]

enum class kcenon::thread::error_code
strong
Enumerator
success 
unknown_error 
operation_canceled 
operation_timeout 
not_implemented 
invalid_argument 
thread_already_running 
thread_not_running 
thread_start_failure 
thread_join_failure 
queue_full 
queue_empty 
queue_stopped 
queue_busy 
job_creation_failed 
job_execution_failed 
job_invalid 
resource_allocation_failed 
resource_limit_reached 
mutex_error 
deadlock_detected 
condition_variable_error 
io_error 
file_not_found 
success 
unknown_error 
operation_canceled 
operation_timeout 
not_implemented 
invalid_argument 
thread_already_running 
thread_not_running 
thread_start_failure 
thread_join_failure 
queue_full 
queue_empty 
queue_stopped 
queue_busy 
job_creation_failed 
job_execution_failed 
job_invalid 
resource_allocation_failed 
resource_limit_reached 
mutex_error 
deadlock_detected 
condition_variable_error 
io_error 
file_not_found 
circuit_open 

Circuit breaker is open, request rejected.

circuit_half_open 

Circuit breaker is in half-open state.

Definition at line 47 of file error_handling.h.

47 {
48 // General errors (-100 to -109)
49 success = 0,
50 unknown_error = -101,
51 operation_canceled = -102,
52 operation_timeout = -103,
53 not_implemented = -104,
54 invalid_argument = -105,
55
56 // Thread errors (-110 to -119)
58 thread_not_running = -111,
61
62 // Queue errors (-120 to -129)
63 queue_full = -120,
64 queue_empty = -121,
65 queue_stopped = -122,
66 queue_busy = -123, // Queue is temporarily busy with concurrent operations
67
68 // Job errors (-130 to -139)
71 job_invalid = -132,
72
73 // Resource errors (-140 to -149)
76
77 // Synchronization errors (-150 to -159)
78 mutex_error = -150,
79 deadlock_detected = -151,
81
82 // IO errors (-160 to -169)
83 io_error = -160,
84 file_not_found = -161,
85
86 // Circuit breaker errors (-170 to -179)
87 circuit_open = -170,
88 circuit_half_open = -171
89};
@ circuit_half_open
Circuit breaker is in half-open state.
@ circuit_open
Circuit breaker is open, request rejected.

◆ job_priority

enum class kcenon::thread::job_priority
strong

Priority levels for job scheduling.

Jobs with higher priority values are typically executed before lower priority jobs. This enum provides a standardized set of priority levels for use with composition.

Enumerator
lowest 

Lowest priority, executed when no other jobs are pending.

low 

Low priority, background tasks.

normal 

Normal priority, default for most jobs.

high 

High priority, time-sensitive tasks.

highest 

Highest priority, critical tasks.

realtime 

Real-time priority, should be used sparingly.

Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/job_builder.h.

Definition at line 47 of file job.h.

48 {
49 lowest = 0,
50 low = 1,
51 normal = 2,
52 high = 3,
53 highest = 4,
54 realtime = 5
55 };
@ low
Between low and high watermark.
@ high
Above high_watermark, approaching capacity.
@ lowest
Lowest priority, executed when no other jobs are pending.
@ realtime
Real-time priority, should be used sparingly.
@ highest
Highest priority, critical tasks.
@ normal
Normal priority, default for most jobs.

◆ job_types

enum class kcenon::thread::job_types : uint8_t
strong

Defines different types of jobs for a typed thread pool.

Each job in a typed thread pool can be assigned one of these types (RealTime, Batch, Background) to determine which specialized worker threads will process them. This enum uses uint8_t as its underlying type to minimize storage overhead.

Enumerator
RealTime 

Real-time job requiring immediate response.

Batch 

Batch processing job for throughput optimization.

Background 

Background job for low-type maintenance tasks.

Definition at line 32 of file job_types.h.

33 {
34 RealTime,
35 Batch,
37 };
@ Batch
Batch processing job for throughput optimization.
@ Background
Background job for low-type maintenance tasks.
@ RealTime
Real-time job requiring immediate response.

◆ log_level

enum class kcenon::thread::log_level
strong

Logging severity levels (legacy).

Deprecated
Since v1.0.0. Use kcenon::thread::log_level_v2 (from <kcenon/thread/core/log_level.h>) or common::interfaces::log_level (from common_system) instead. Will be removed in v2.0.0. See Issue #261 for migration details.

NOTE: [[deprecated]] is applied at the thread_logger member-function level (log/set_level/log_error) rather than on this enum itself, because this type is still referenced internally by the SDOF-safe shutdown helpers. Using log_level via a deprecated API emits a warning; direct use without the logger does not.

Enumerator
trace 
debug 
info 
warning 
error 
critical 

Definition at line 42 of file thread_logger.h.

42 {
43 trace,
44 debug,
45 info,
46 warning,
47 error,
49};
Represents an error in the thread system.
@ critical
At or above max_size, queue is full.
@ trace
Finest-grained informational events.
@ debug
Fine-grained informational events for debugging.
@ info
Informational messages highlighting progress.

◆ log_level_v2

enum class kcenon::thread::log_level_v2 : uint8_t
strong

Logging severity levels with explicit ascending values.

Standard ascending order (matches syslog, log4j, spdlog conventions):

  • Lower values = less severe (trace)
  • Higher values = more severe (critical)

This enables natural comparison: if (level >= log_level_v2::warn) { ... }

Enumerator
trace 

Finest-grained informational events.

debug 

Fine-grained informational events for debugging.

info 

Informational messages highlighting progress.

warn 

Potentially harmful situations.

error 

Error events that might still allow continuation.

critical 

Severe error events that lead to termination.

off 

Special level to disable logging.

Definition at line 27 of file log_level.h.

27 : uint8_t {
28 trace = 0,
29 debug = 1,
30 info = 2,
31 warn = 3,
32 error = 4,
33 critical = 5,
34 off = 6
35};
@ warn
Potentially harmful situations.
@ off
Special level to disable logging.

◆ retry_strategy

enum class kcenon::thread::retry_strategy
strong

Defines the strategy for calculating delay between retry attempts.

Enumerator
none 

No retry.

fixed 

Fixed delay between retries.

linear 

Linearly increasing delay.

exponential_backoff 

Exponentially increasing delay with optional jitter.

Definition at line 28 of file retry_policy.h.

29 {
30 none,
31 fixed,
32 linear,
34 };
@ none
Below low_watermark, queue is healthy.
@ exponential_backoff
Exponentially increasing delay with optional jitter.
@ fixed
Fixed delay between retries.

◆ scaling_direction

Scaling direction for autoscaling decisions.

Enumerator
none 

No scaling needed.

up 

Scale up (add workers)

down 

Scale down (remove workers)

Definition at line 23 of file scaling_metrics.h.

24 {
25 none,
26 up,
27 down
28 };
@ up
Scale up (add workers)
@ down
Scale down (remove workers)

◆ scaling_reason

enum class kcenon::thread::scaling_reason
strong

Reason for scaling decision.

Enumerator
queue_depth 

Queue depth threshold exceeded.

worker_utilization 

Worker utilization threshold exceeded.

latency 

Latency threshold exceeded.

manual 

Manual trigger via API.

scheduled 

Scheduled scaling event.

Definition at line 33 of file scaling_metrics.h.

34 {
37 latency,
38 manual,
40 };
@ manual
Manual trigger via API.
@ scheduled
Scheduled scaling event.
@ latency
Latency threshold exceeded.
@ worker_utilization
Worker utilization threshold exceeded.
@ queue_depth
Queue depth threshold exceeded.

◆ scheduling_policy

Enumeration of scheduling policies.

Enumerator
fifo 

First-in, first-out scheduling.

lifo 

Last-in, first-out scheduling.

priority 

Priority-based scheduling.

work_stealing 

Work-stealing scheduling.

Definition at line 37 of file worker_policy.h.

37 {
38 fifo,
39 lifo,
40 priority,
42 };
@ work_stealing
Work-stealing scheduling.
@ lifo
Last-in, first-out scheduling.
@ priority
Priority-based scheduling.
@ fifo
First-in, first-out scheduling.

◆ steal_backoff_strategy

enum class kcenon::thread::steal_backoff_strategy : std::uint8_t
strong

Backoff strategies for work-stealing operations.

When a steal attempt fails, workers use backoff strategies to reduce contention and allow other threads to make progress. Different strategies offer different trade-offs between responsiveness and CPU usage.

Strategy Comparison

Strategy Behavior Best For
fixed Constant delay Predictable workloads
linear Increasing delay Moderate contention
exponential Rapidly increasing High contention
adaptive_jitter Exponential + random Variable workloads
Enumerator
fixed 

Constant delay between steal attempts.

linear 

Linear increase: delay = initial * (attempt + 1)

exponential 

Exponential increase: delay = initial * 2^attempt.

adaptive_jitter 

Exponential with random jitter for anti-correlation.

Definition at line 39 of file steal_backoff_strategy.h.

40{
41 fixed,
42 linear,
45};
@ adaptive_jitter
Exponential with random jitter for anti-correlation.

◆ steal_policy

enum class kcenon::thread::steal_policy
strong

Policy for selecting steal victims.

When a worker's local queue is empty, it attempts to steal work from other workers. This enum defines how victims are selected.

Enumerator
random 

Random victim selection (default, good load distribution)

round_robin 

Sequential victim selection (deterministic, fair)

adaptive 

Select based on queue sizes (best for uneven loads)

Definition at line 50 of file worker_policy.h.

50 {
51 random,
54 };

◆ thread_conditions

enum class kcenon::thread::thread_conditions : uint8_t
strong

Enumeration of various states in a thread's lifecycle.

Represents distinct conditions that a thread may occupy during its execution lifecycle. This enum class is backed by uint8_t for compact storage.

Value Description
Created The thread object is constructed but not yet started.
Waiting The thread is started and idle, waiting for work.
Working The thread is actively processing work.
Stopping The thread is in the process of stopping its work.
Stopped The thread has fully stopped.
Enumerator
Created 

Thread created but not started.

Waiting 

Thread waiting for work or tasks.

Working 

Thread currently processing a task.

Stopping 

Thread in the process of stopping.

Stopped 

Thread fully stopped.

Definition at line 40 of file thread_conditions.h.

41 {
42 Created,
43 Waiting,
44 Working,
45 Stopping,
46 Stopped,
47 };
@ Created
Thread created but not started.
@ Waiting
Thread waiting for work or tasks.
@ Stopping
Thread in the process of stopping.
@ Working
Thread currently processing a task.
@ Stopped
Thread fully stopped.

◆ worker_state

enum class kcenon::thread::worker_state
strong

Enumeration of worker states.

Enumerator
created 

Worker created but not started.

starting 

Worker is starting up.

active 

Worker is actively processing jobs.

idle 

Worker is idle, waiting for work.

stopping 

Worker is shutting down.

stopped 

Worker has stopped.

Definition at line 25 of file worker_policy.h.

25 {
26 created,
27 starting,
28 active,
29 idle,
30 stopping,
31 stopped
32 };
@ starting
Worker is starting up.
@ stopping
Worker is shutting down.
@ active
Worker is actively processing jobs.
@ created
Worker created but not started.
@ idle
Worker is idle, waiting for work.
@ stopped
Worker has stopped.

Function Documentation

◆ backpressure_policy_to_string()

auto kcenon::thread::backpressure_policy_to_string ( backpressure_policy policy) -> std::string
inlinenodiscard

Converts backpressure_policy to human-readable string.

Parameters
policyThe policy to convert.
Returns
String representation of the policy.
Examples
config_example.cpp.

Definition at line 115 of file backpressure_config.h.

116 {
117 switch (policy)
118 {
119 case backpressure_policy::block: return "block";
120 case backpressure_policy::drop_oldest: return "drop_oldest";
121 case backpressure_policy::drop_newest: return "drop_newest";
122 case backpressure_policy::callback: return "callback";
123 case backpressure_policy::adaptive: return "adaptive";
124 default: return "unknown";
125 }
126 }

References adaptive, block, callback, drop_newest, and drop_oldest.

Referenced by kcenon::thread::backpressure_job_queue::to_string().

Here is the caller graph for this function:

◆ create_pool_builder()

template<detail::JobType job_type = job_types>
typed_thread_pool_builder< job_type > kcenon::thread::create_pool_builder ( )
nodiscard

Convenience function to create a builder.

Returns
A new thread pool builder instance

Definition at line 169 of file pool_builder.h.

169 {
171 }
Typed thread pool builder template.

◆ dag_failure_policy_to_string()

auto kcenon::thread::dag_failure_policy_to_string ( dag_failure_policy policy) -> std::string
inlinenodiscard

Convert dag_failure_policy to string representation.

Parameters
policyThe policy to convert
Returns
String representation of the policy
Examples
config_example.cpp.

Definition at line 54 of file dag_config.h.

55 {
56 switch (policy)
57 {
58 case dag_failure_policy::fail_fast: return "fail_fast";
59 case dag_failure_policy::continue_others: return "continue_others";
60 case dag_failure_policy::retry: return "retry";
61 case dag_failure_policy::fallback: return "fallback";
62 default: return "unknown";
63 }
64 }

References continue_others, fail_fast, fallback, and retry.

◆ dag_job_state_to_string()

auto kcenon::thread::dag_job_state_to_string ( dag_job_state state) -> std::string
inlinenodiscard

Convert dag_job_state to string representation.

Parameters
stateThe state to convert
Returns
String representation of the state

Definition at line 60 of file dag_job.h.

61 {
62 switch (state)
63 {
64 case dag_job_state::pending: return "pending";
65 case dag_job_state::ready: return "ready";
66 case dag_job_state::running: return "running";
67 case dag_job_state::completed: return "completed";
68 case dag_job_state::failed: return "failed";
69 case dag_job_state::cancelled: return "cancelled";
70 case dag_job_state::skipped: return "skipped";
71 default: return "unknown";
72 }
73 }

References cancelled, completed, failed, pending, ready, running, and skipped.

Referenced by kcenon::thread::dag_scheduler::to_dot(), kcenon::thread::dag_scheduler::to_json(), and kcenon::thread::dag_job::to_string().

Here is the caller graph for this function:

◆ error_code_to_string()

std::string kcenon::thread::error_code_to_string ( error_code code)
inline

Converts an error_code to a string representation.

Parameters
codeThe error code to convert
Returns
A human-readable string describing the error

Definition at line 92 of file error_handling.h.

92 {
93 using map_entry = std::pair<error_code, std::string_view>;
94 static constexpr map_entry kMap[] = {
95 {error_code::success, "Success"},
96 {error_code::unknown_error, "Unknown error"},
97 {error_code::operation_canceled, "Operation canceled"},
98 {error_code::operation_timeout, "Operation timed out"},
99 {error_code::not_implemented, "Not implemented"},
100 {error_code::invalid_argument, "Invalid argument"},
101 {error_code::thread_already_running, "Thread is already running"},
102 {error_code::thread_not_running, "Thread is not running"},
103 {error_code::thread_start_failure, "Failed to start thread"},
104 {error_code::thread_join_failure, "Failed to join thread"},
105 {error_code::queue_full, "Queue is full"},
106 {error_code::queue_empty, "Queue is empty"},
107 {error_code::queue_stopped, "Queue is stopped"},
108 {error_code::queue_busy, "Queue is busy"},
109 {error_code::job_creation_failed, "Failed to create job"},
110 {error_code::job_execution_failed, "Failed to execute job"},
111 {error_code::job_invalid, "Invalid job"},
112 {error_code::resource_allocation_failed, "Failed to allocate resource"},
113 {error_code::resource_limit_reached, "Resource limit reached"},
114 {error_code::mutex_error, "Mutex error"},
115 {error_code::deadlock_detected, "Deadlock detected"},
116 {error_code::condition_variable_error, "Condition variable error"},
117 {error_code::io_error, "I/O error"},
118 {error_code::file_not_found, "File not found"},
119 };
120 for (const auto& [k, v] : kMap) {
121 if (k == code) return std::string(v);
122 }
123 return std::string("Unknown error code");
124}

References condition_variable_error, deadlock_detected, file_not_found, invalid_argument, io_error, job_creation_failed, job_execution_failed, job_invalid, mutex_error, not_implemented, operation_canceled, operation_timeout, queue_busy, queue_empty, queue_full, queue_stopped, resource_allocation_failed, resource_limit_reached, success, thread_already_running, thread_join_failure, thread_not_running, thread_start_failure, and unknown_error.

Referenced by kcenon::thread::thread_error_category::message(), to_error_info(), and kcenon::thread::error::to_string().

Here is the caller graph for this function:

◆ get_all_job_types()

auto kcenon::thread::get_all_job_types ( void ) -> std::vector<job_types>
inlinenodiscard

Returns a vector containing all possible job_types values.

Returns
A std::vector<job_types> with [RealTime, Batch, Background].

This function is useful when iterating over all defined types (e.g. for logging, UI selection, or testing).

Example

for (auto type : all_types()) {
std::cout << to_string(type) << std::endl;
}
// Output:
// REALTIME
// BATCH
// BACKGROUND
constexpr std::string_view to_string(log_level_v2 level) noexcept
Convert log_level_v2 to string representation.
Definition log_level.h:40
auto all_types(void) -> std::vector< test_priority >
Converts a string to a job_types value.
Definition test_type.h:62

Definition at line 106 of file job_types.h.

107 {
108 return { job_types::RealTime, job_types::Batch, job_types::Background };
109 }

References Background, Batch, and RealTime.

◆ get_all_thread_conditions()

auto kcenon::thread::get_all_thread_conditions ( void ) -> std::vector<thread_conditions>
inlinenodiscard

Retrieves a vector containing all possible thread_conditions values.

Returns
A std::vector of all enumerators in thread_conditions, in ascending order.

This can be useful for iteration, logging, or building UI elements that list thread states. For example:

for (auto cond : all_types()) {
std::cout << to_string(cond) << std::endl;
}

Definition at line 108 of file thread_conditions.h.

109 {
110 return { thread_conditions::Created, thread_conditions::Waiting, thread_conditions::Working,
111 thread_conditions::Stopping, thread_conditions::Stopped };
112 }

References Created, Stopped, Stopping, Waiting, and Working.

◆ get_error_code()

error_code kcenon::thread::get_error_code ( const common::error_info & info)
inline

Extract thread::error_code from a common::error_info.

Parameters
infoThe error_info from a common::Result or common::VoidResult
Returns
The corresponding thread::error_code

Example:

auto result = some_operation();
if (result.is_err()) {
auto code = get_error_code(result.error());
if (code == error_code::queue_full) {
// handle queue full case
}
}
A template class representing either a value or an error.
error_code get_error_code(const common::error_info &info)
Extract thread::error_code from a common::error_info.

Definition at line 220 of file error_handling.h.

220 {
221 return static_cast<error_code>(info.code);
222}
error_code
Strongly typed error codes for thread system operations.

References info.

◆ make_atomic_shared()

template<typename T , typename... Args>
atomic_shared_ptr< T > kcenon::thread::make_atomic_shared ( Args &&... args)
nodiscard

Make an atomic_shared_ptr with a new object.

Template Parameters
TObject type
ArgsConstructor argument types
Parameters
argsConstructor arguments
Returns
atomic_shared_ptr containing new object
Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/atomic_shared_ptr.h.

Definition at line 283 of file atomic_shared_ptr.h.

283 {
284 return atomic_shared_ptr<T>(std::make_shared<T>(std::forward<Args>(args)...));
285}

◆ make_error_code()

std::error_code kcenon::thread::make_error_code ( error_code e)
inlinenoexcept

Creates a std::error_code from a thread_system error_code.

Parameters
eThe thread_system error_code
Returns
std::error_code representing the error

Definition at line 290 of file error_handling.h.

290 {
291 return std::error_code(static_cast<int>(e), thread_category());
292}
const std::error_category & thread_category() noexcept
Gets the singleton instance of thread_error_category.

References thread_category().

Here is the call graph for this function:

◆ make_error_condition()

std::error_condition kcenon::thread::make_error_condition ( error_code e)
inlinenoexcept

Creates a std::error_condition from a thread_system error_code.

Parameters
eThe thread_system error_code
Returns
std::error_condition representing the error

Definition at line 299 of file error_handling.h.

299 {
300 return std::error_condition(static_cast<int>(e), thread_category());
301}

References thread_category().

Here is the call graph for this function:

◆ make_error_result() [1/2]

common::VoidResult kcenon::thread::make_error_result ( error_code code,
const std::string & message = "" )
inline

Create a common::VoidResult error from a thread::error_code.

Parameters
codeThe thread-specific error code
messageOptional additional message
Returns
A common::VoidResult in error state

Example:

if (queue_is_full) {
}
return common::ok();
common::VoidResult make_error_result(error_code code, const std::string &message="")
Create a common::VoidResult error from a thread::error_code.
Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/job_builder.h.

Definition at line 178 of file error_handling.h.

178 {
179 return common::VoidResult(to_error_info(code, message));
180}
common::error_info to_error_info(error_code code, const std::string &message="")
Convert a thread::error_code to common::error_info.

References to_error_info().

Referenced by kcenon::thread::dag_scheduler::add_dependency(), kcenon::thread::backpressure_job_queue::apply_backpressure(), kcenon::thread::cancellation_token::check_cancelled(), kcenon::thread::enhanced_cancellation_token::check_cancelled(), kcenon::thread::dag_job::do_work(), kcenon::thread::future_job< R >::do_work(), kcenon::thread::job_builder::built_job::do_work(), kcenon::thread::protected_job::do_work(), kcenon::thread::backpressure_job_queue::enqueue(), kcenon::thread::backpressure_job_queue::enqueue_batch(), kcenon::thread::dag_scheduler::execute(), kcenon::thread::dag_scheduler::execute_all(), kcenon::thread::dag_scheduler::execute_job(), kcenon::thread::cancellable_future< R >::get(), kcenon::thread::cancellable_future< void >::get(), kcenon::thread::cancellable_future< R >::get_for(), kcenon::thread::cancellable_future< void >::get_for(), kcenon::thread::backpressure_job_queue::handle_adaptive_policy(), kcenon::thread::backpressure_job_queue::handle_block_policy(), kcenon::thread::backpressure_job_queue::handle_callback_policy(), kcenon::thread::circuit_breaker_policy::on_enqueue(), kcenon::thread::dag_scheduler::remove_job(), kcenon::thread::dag_scheduler::reset(), and kcenon::thread::thread_pool::submit_wait_any().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ make_error_result() [2/2]

template<typename T >
common::Result< T > kcenon::thread::make_error_result ( error_code code,
const std::string & message = "" )

Create a common::Result<T> error from a thread::error_code.

Template Parameters
TThe value type of the result
Parameters
codeThe thread-specific error code
messageOptional additional message
Returns
A common::Result<T> in error state

Example:

common::Result<int> get_value() {
if (not_ready) {
}
return common::Result<int>::ok(42);
}

Definition at line 200 of file error_handling.h.

200 {
201 return common::Result<T>(to_error_info(code, message));
202}

References to_error_info().

Here is the call graph for this function:

◆ make_exceptional_future()

template<typename T >
pool_future< T > kcenon::thread::make_exceptional_future ( std::exception_ptr exception)

Create a future that is already ready with an exception.

Definition at line 201 of file future_extensions.h.

201 {
202 pool_promise<T> promise;
203 auto future = promise.get_future();
204 promise.set_exception(exception);
205 return future;
206 }
A promise that can schedule work on a thread pool.
pool_future< T > get_future()
Get the associated future.
void set_exception(std::exception_ptr exception)
Set an exception.

References kcenon::thread::pool_promise< T >::get_future(), and kcenon::thread::pool_promise< T >::set_exception().

Here is the call graph for this function:

◆ make_job()

auto kcenon::thread::make_job ( ) -> job_builder
inlinenodiscard
Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/job_builder.h.

Definition at line 432 of file job_builder.h.

433 {
434 return job_builder{};
435 }
Fluent builder for creating and configuring jobs with composition.
Definition job_builder.h:98

◆ make_lockfree_queue_adapter()

auto kcenon::thread::make_lockfree_queue_adapter ( ) -> std::unique_ptr<pool_queue_adapter_interface>
inlinenodiscard

Create a lock-free queue adapter.

Returns
Unique pointer to pool_queue_adapter_interface

Definition at line 269 of file policy_queue_adapter.h.

271{
272 return std::make_unique<lockfree_queue_adapter>();
273}

◆ make_policy_queue_adapter() [1/2]

template<typename PolicyQueueType >
auto kcenon::thread::make_policy_queue_adapter ( ) -> std::unique_ptr<pool_queue_adapter_interface>
nodiscard

Create a pool_queue_adapter from a policy_queue type.

Template Parameters
PolicyQueueTypeA policy_queue instantiation
Returns
Unique pointer to pool_queue_adapter_interface
auto make_policy_queue_adapter() -> std::unique_ptr< pool_queue_adapter_interface >
Create a pool_queue_adapter from a policy_queue type.

Definition at line 225 of file policy_queue_adapter.h.

227{
228 using adapter_type = policy_queue_adapter<
229 typename PolicyQueueType::sync_policy_type,
230 typename PolicyQueueType::bound_policy_type,
231 typename PolicyQueueType::overflow_policy_type
232 >;
233 return std::make_unique<adapter_type>();
234}
Adapter for policy_queue to pool_queue_adapter_interface.

◆ make_policy_queue_adapter() [2/2]

template<typename PolicyQueueType >
auto kcenon::thread::make_policy_queue_adapter ( typename PolicyQueueType::bound_policy_type bound_policy) -> std::unique_ptr<pool_queue_adapter_interface>
nodiscard

Create a pool_queue_adapter with bound policy.

Template Parameters
PolicyQueueTypeA policy_queue instantiation
Parameters
bound_policyBound policy configuration
Returns
Unique pointer to pool_queue_adapter_interface

Definition at line 243 of file policy_queue_adapter.h.

246{
247 using adapter_type = policy_queue_adapter<
248 typename PolicyQueueType::sync_policy_type,
249 typename PolicyQueueType::bound_policy_type,
250 typename PolicyQueueType::overflow_policy_type
251 >;
252 return std::make_unique<adapter_type>(std::move(bound_policy));
253}

◆ make_ready_future() [1/2]

pool_future< void > kcenon::thread::make_ready_future ( )
inline

Create a future that is already ready with void.

Definition at line 190 of file future_extensions.h.

190 {
191 pool_promise<void> promise;
192 auto future = promise.get_future();
193 promise.set_value();
194 return future;
195 }
void set_value(const T &value)
Set the value.

References kcenon::thread::pool_promise< T >::get_future(), and kcenon::thread::pool_promise< T >::set_value().

Here is the call graph for this function:

◆ make_ready_future() [2/2]

template<typename T >
pool_future< std::decay_t< T > > kcenon::thread::make_ready_future ( T && value)

Create a future that is already ready with a value.

Definition at line 180 of file future_extensions.h.

180 {
182 auto future = promise.get_future();
183 promise.set_value(std::forward<T>(value));
184 return future;
185 }

References kcenon::thread::pool_promise< T >::get_future(), and kcenon::thread::pool_promise< T >::set_value().

Here is the call graph for this function:

◆ make_standard_queue_adapter()

auto kcenon::thread::make_standard_queue_adapter ( ) -> std::unique_ptr<pool_queue_adapter_interface>
inlinenodiscard

Create a standard_queue adapter.

Returns
Unique pointer to pool_queue_adapter_interface

Definition at line 259 of file policy_queue_adapter.h.

261{
262 return std::make_unique<standard_queue_adapter>();
263}

◆ optional_error_to_result() [1/2]

result< void > kcenon::thread::optional_error_to_result ( const std::optional< std::string > & error)
inline

Definition at line 617 of file error_handling.h.

617 {
618 if (error) {
619 return result<void>(kcenon::thread::error{error_code::unknown_error, *error});
620 }
621 return result<void>();
622}

References unknown_error.

◆ optional_error_to_result() [2/2]

template<typename T >
result< T > kcenon::thread::optional_error_to_result ( const std::optional< std::string > & error,
T && value )

Definition at line 609 of file error_handling.h.

609 {
610 if (error) {
611 return result<T>(kcenon::thread::error{error_code::unknown_error, *error});
612 }
613 return result<T>(std::forward<T>(value));
614}

References unknown_error.

◆ parse_log_level()

log_level_v2 kcenon::thread::parse_log_level ( std::string_view str)
inlinenoexcept

Parse string to log_level_v2.

Definition at line 75 of file log_level.h.

75 {
76 if (str == "trace" || str == "TRACE") return log_level_v2::trace;
77 if (str == "debug" || str == "DEBUG") return log_level_v2::debug;
78 if (str == "info" || str == "INFO") return log_level_v2::info;
79 if (str == "warn" || str == "WARN" || str == "warning" || str == "WARNING")
80 return log_level_v2::warn;
81 if (str == "error" || str == "ERROR") return log_level_v2::error;
82 if (str == "critical" || str == "CRITICAL" || str == "fatal" || str == "FATAL")
83 return log_level_v2::critical;
84 if (str == "off" || str == "OFF") return log_level_v2::off;
85 return log_level_v2::info; // default
86}

References critical, debug, error, info, off, trace, and warn.

◆ pressure_level_to_string()

auto kcenon::thread::pressure_level_to_string ( pressure_level level) -> std::string
inlinenodiscard

Converts pressure_level to human-readable string.

Parameters
levelThe pressure level to convert.
Returns
String representation of the pressure level.

Definition at line 98 of file backpressure_config.h.

99 {
100 switch (level)
101 {
102 case pressure_level::none: return "none";
103 case pressure_level::low: return "low";
104 case pressure_level::high: return "high";
105 case pressure_level::critical: return "critical";
106 default: return "unknown";
107 }
108 }

References critical, high, low, and none.

Referenced by kcenon::thread::backpressure_job_queue::to_string().

Here is the caller graph for this function:

◆ result_to_optional_error()

std::optional< std::string > kcenon::thread::result_to_optional_error ( const result< void > & res)
inline

Definition at line 625 of file error_handling.h.

625 {
626 if (res) {
627 return std::nullopt;
628 }
629 return res.get_error().to_string();
630}
std::string to_string() const
Converts the error to a string representation.
error & get_error() &
Gets the error.

References kcenon::thread::result< T >::get_error(), and kcenon::thread::error::to_string().

Here is the call graph for this function:

◆ result_to_pair()

template<typename T >
std::pair< std::optional< T >, std::optional< std::string > > kcenon::thread::result_to_pair ( const result< T > & res)

Definition at line 633 of file error_handling.h.

633 {
634 if (res) {
635 return {res.value(), std::nullopt};
636 }
637 return {std::nullopt, res.get_error().to_string()};
638}
error & get_error() &
Gets the error.
T & value() &
Gets the value.

References kcenon::thread::result< T >::get_error(), kcenon::thread::error::to_string(), and kcenon::thread::result< T >::value().

Here is the call graph for this function:

◆ safe_retire_hazard()

template<typename T >
void kcenon::thread::safe_retire_hazard ( T * p)
Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/safe_hazard_pointer.h.

Definition at line 460 of file safe_hazard_pointer.h.

460 {
461 if (p == nullptr) {
462 return;
463 }
464 safe_hazard_pointer_domain::instance().retire(
465 p,
466 [](void* ptr) { delete static_cast<T*>(ptr); }
467 );
468}

References kcenon::thread::safe_hazard_pointer_domain::instance(), and kcenon::thread::safe_hazard_pointer_domain::retire().

Referenced by kcenon::thread::typed_safe_hazard_domain< T >::retire().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ should_log()

bool kcenon::thread::should_log ( log_level_v2 message_level,
log_level_v2 min_level )
constexprnoexcept

Check if a log level should be logged given a minimum level.

With ascending order, we log if message_level >= min_level

Definition at line 65 of file log_level.h.

65 {
66 if (min_level == log_level_v2::off) {
67 return false;
68 }
69 return static_cast<uint8_t>(message_level) >= static_cast<uint8_t>(min_level);
70}

References off.

◆ thread_category()

const std::error_category & kcenon::thread::thread_category ( )
inlinenoexcept

Gets the singleton instance of thread_error_category.

Returns
Reference to the thread_error_category singleton

Definition at line 280 of file error_handling.h.

280 {
281 static thread_error_category instance;
282 return instance;
283}
std::error_category implementation for thread_system errors

Referenced by make_error_code(), and make_error_condition().

Here is the caller graph for this function:

◆ to_error_info()

common::error_info kcenon::thread::to_error_info ( error_code code,
const std::string & message = "" )
inline

Convert a thread::error_code to common::error_info.

Parameters
codeThe thread-specific error code
messageOptional additional message (defaults to error_code_to_string)
Returns
A common::error_info structure

Example:

auto info = to_error_info(error_code::queue_full, "Custom message");
return common::VoidResult(info);

Definition at line 156 of file error_handling.h.

156 {
157 return common::error_info{
158 static_cast<int>(code),
159 message.empty() ? error_code_to_string(code) : message,
160 "thread_system"
161 };
162}
std::string error_code_to_string(error_code code)
Converts an error_code to a string representation.

References error_code_to_string().

Referenced by make_error_result(), and kcenon::thread::dag_scheduler::on_job_failed().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ to_string() [1/8]

const char * kcenon::thread::to_string ( enhanced_steal_policy policy)
constexpr

Convert enhanced_steal_policy to string representation.

Parameters
policyThe policy to convert
Returns
String name of the policy

Definition at line 52 of file enhanced_steal_policy.h.

53{
54 switch (policy)
55 {
56 case enhanced_steal_policy::random:
57 return "random";
58 case enhanced_steal_policy::round_robin:
59 return "round_robin";
60 case enhanced_steal_policy::adaptive:
61 return "adaptive";
62 case enhanced_steal_policy::numa_aware:
63 return "numa_aware";
64 case enhanced_steal_policy::locality_aware:
65 return "locality_aware";
66 case enhanced_steal_policy::hierarchical:
67 return "hierarchical";
68 default:
69 return "unknown";
70 }
71}

References adaptive, hierarchical, locality_aware, numa_aware, random, and round_robin.

◆ to_string() [2/8]

std::string_view kcenon::thread::to_string ( job_types job_type)
nodiscardconstexpr

Converts a job_types value to its corresponding string representation.

Parameters
job_typeThe job_types value to convert.
Returns
A std::string_view containing one of "REALTIME", "BATCH", "BACKGROUND", or "UNKNOWN" if job_type is out of expected range.

Example

std::string_view sv = to_string(p); // "REALTIME"

Definition at line 81 of file job_types.h.

82 {
83 auto index = static_cast<size_t>(job_type);
84 return (index < job_detail::job_type_count) ? job_detail::job_type_strings[index]
85 : "UNKNOWN";
86 }

References kcenon::thread::job_detail::job_type_count, and kcenon::thread::job_detail::job_type_strings.

◆ to_string() [3/8]

std::string_view kcenon::thread::to_string ( log_level_v2 level)
constexprnoexcept

Convert log_level_v2 to string representation.

Definition at line 40 of file log_level.h.

40 {
41 switch (level) {
42 case log_level_v2::trace: return "TRACE";
43 case log_level_v2::debug: return "DEBUG";
44 case log_level_v2::info: return "INFO";
45 case log_level_v2::warn: return "WARN";
46 case log_level_v2::error: return "ERROR";
47 case log_level_v2::critical: return "CRITICAL";
48 case log_level_v2::off: return "OFF";
49 default: return "UNKNOWN";
50 }
51}

References critical, debug, error, info, off, trace, and warn.

Referenced by std::formatter< kcenon::thread::job_types >::format(), std::formatter< kcenon::thread::job_types, wchar_t >::format(), std::formatter< kcenon::thread::thread_conditions >::format(), and std::formatter< kcenon::thread::thread_conditions, wchar_t >::format().

Here is the caller graph for this function:

◆ to_string() [4/8]

const char * kcenon::thread::to_string ( scheduling_policy policy)
constexpr

Convert scheduling policy to string representation.

Definition at line 153 of file worker_policy.h.

153 {
154 switch (policy) {
155 case scheduling_policy::fifo: return "fifo";
156 case scheduling_policy::lifo: return "lifo";
157 case scheduling_policy::priority: return "priority";
158 case scheduling_policy::work_stealing: return "work_stealing";
159 default: return "unknown";
160 }
161 }

References fifo, lifo, priority, and work_stealing.

◆ to_string() [5/8]

const char * kcenon::thread::to_string ( steal_backoff_strategy strategy)
constexpr

Convert steal_backoff_strategy to string representation.

Parameters
strategyThe strategy to convert
Returns
String name of the strategy

Definition at line 224 of file steal_backoff_strategy.h.

225{
226 switch (strategy)
227 {
228 case steal_backoff_strategy::fixed:
229 return "fixed";
230 case steal_backoff_strategy::linear:
231 return "linear";
232 case steal_backoff_strategy::exponential:
233 return "exponential";
234 case steal_backoff_strategy::adaptive_jitter:
235 return "adaptive_jitter";
236 default:
237 return "unknown";
238 }
239}

References adaptive_jitter, exponential, fixed, and linear.

◆ to_string() [6/8]

const char * kcenon::thread::to_string ( steal_policy policy)
constexpr

Convert steal policy to string representation.

Definition at line 166 of file worker_policy.h.

166 {
167 switch (policy) {
168 case steal_policy::random: return "random";
169 case steal_policy::round_robin: return "round_robin";
170 case steal_policy::adaptive: return "adaptive";
171 default: return "unknown";
172 }
173 }

References adaptive, random, and round_robin.

◆ to_string() [7/8]

std::string_view kcenon::thread::to_string ( thread_conditions condition)
nodiscardconstexpr

Converts a thread_conditions value to its corresponding string representation.

Parameters
conditionThe thread_conditions value to convert.
Returns
A std::string_view representing the condition name. If the value is out of range, returns "UNKNOWN".

Example:

auto name = to_string(state); // "working"

Definition at line 88 of file thread_conditions.h.

89 {
90 auto index = static_cast<size_t>(condition);
91 return (index < job_detail::thread_conditions_count)
92 ? job_detail::thread_conditions_strings[index]
93 : "UNKNOWN";
94 }

References kcenon::thread::job_detail::thread_conditions_count, and kcenon::thread::job_detail::thread_conditions_strings.

◆ to_string() [8/8]

const char * kcenon::thread::to_string ( worker_state state)
constexpr

Convert worker state to string representation.

Definition at line 138 of file worker_policy.h.

138 {
139 switch (state) {
140 case worker_state::created: return "created";
141 case worker_state::starting: return "starting";
142 case worker_state::active: return "active";
143 case worker_state::idle: return "idle";
144 case worker_state::stopping: return "stopping";
145 case worker_state::stopped: return "stopped";
146 default: return "unknown";
147 }
148 }

References active, created, idle, starting, stopped, and stopping.

◆ wait_for_all()

template<typename... Futures>
void kcenon::thread::wait_for_all ( Futures &... futures)

Wait for all futures to complete.

Definition at line 212 of file future_extensions.h.

212 {
213 (futures.wait(), ...);
214 }

◆ wait_for_any()

template<typename... Futures>
size_t kcenon::thread::wait_for_any ( Futures &... futures)

Wait for any future to complete.

Definition at line 220 of file future_extensions.h.

220 {
221 // Use short timeout-based polling instead of busy-wait
222 // This significantly reduces CPU usage while maintaining responsiveness
223 constexpr auto poll_interval = std::chrono::microseconds(100);
224
225 size_t index = 0;
226 auto check_future = [&](auto& future) {
227 if (future.is_ready()) {
228 return true;
229 }
230 ++index;
231 return false;
232 };
233
234 while (true) {
235 index = 0;
236 if ((check_future(futures) || ...)) {
237 return index;
238 }
239 // Sleep briefly to reduce CPU usage instead of busy-waiting
240 std::this_thread::sleep_for(poll_interval);
241 }
242 }

◆ when_all()

template<typename... Futures>
auto kcenon::thread::when_all ( Futures &&... futures) -> std::future<std::tuple<detail::future_value_type_t<std::decay_t<Futures>>...>>

Wait for all futures to complete and return their results as a tuple.

Template Parameters
FuturesVariadic future types
Parameters
futuresThe futures to wait on
Returns
A future containing a tuple of all results

This function creates a new future that completes when all input futures complete. The result is a tuple containing the values from each future.

Thread Safety

  • Thread-safe. Each input future is accessed from a separate thread.

Exception Handling

  • If any future throws an exception, it will be propagated when get() is called on the returned future.

Usage Example

auto f1 = pool->submit_async([]{ return 1; });
auto f2 = pool->submit_async([]{ return 2.0; });
auto f3 = pool->submit_async([]{ return std::string("hello"); });
auto combined = when_all(std::move(f1), std::move(f2), std::move(f3));
auto [a, b, c] = combined.get();
// a = 1, b = 2.0, c = "hello"
auto when_all(Futures &&... futures) -> std::future< std::tuple< detail::future_value_type_t< std::decay_t< Futures > >... > >
Wait for all futures to complete and return their results as a tuple.

Definition at line 78 of file when_helpers.h.

80{
81 using result_tuple = std::tuple<detail::future_value_type_t<std::decay_t<Futures>>...>;
82
83 auto promise = std::make_shared<std::promise<result_tuple>>();
84 auto result_future = promise->get_future();
85
86 // Store futures in a tuple for processing
87 auto futures_tuple = std::make_shared<std::tuple<std::decay_t<Futures>...>>(
88 std::forward<Futures>(futures)...);
89
90 // Launch async operation to wait for all
91 std::thread([promise, futures_tuple]() mutable {
92 try {
93 result_tuple results;
94 detail::get_all_impl(
95 std::make_index_sequence<sizeof...(Futures)>{},
96 *futures_tuple,
97 results);
98 promise->set_value(std::move(results));
99 } catch (...) {
100 promise->set_exception(std::current_exception());
101 }
102 }).detach();
103
104 return result_future;
105}

References kcenon::thread::detail::get_all_impl().

Here is the call graph for this function:

◆ when_all_empty()

auto kcenon::thread::when_all_empty ( ) -> std::future<std::tuple<>>
inline

Overload of when_all for no arguments.

Definition at line 110 of file when_helpers.h.

111{
112 std::promise<std::tuple<>> promise;
113 promise.set_value(std::tuple<>{});
114 return promise.get_future();
115}

◆ when_any() [1/2]

template<typename T >
auto kcenon::thread::when_any ( std::vector< std::future< T > > && futures) -> std::future<T>

Wait for any future to complete and return its result.

Template Parameters
TThe common result type of all futures
Parameters
futuresVector of futures
Returns
A future containing the first completed result

This function creates a new future that completes when any of the input futures completes. The result is the value from the first completed future.

Thread Safety

  • Thread-safe. Uses atomic operations for completion tracking.

Usage Example

std::vector<std::future<int>> futures;
futures.push_back(pool->submit_async([]{ return fetch_from_server_a(); }));
futures.push_back(pool->submit_async([]{ return fetch_from_server_b(); }));
auto first = when_any(std::move(futures));
int result = first.get(); // First completed result
auto when_any(std::vector< std::future< T > > &&futures) -> std::future< T >
Wait for any future to complete and return its result.

Definition at line 141 of file when_helpers.h.

143{
144 if (futures.empty()) {
145 std::promise<T> promise;
146 promise.set_exception(
147 std::make_exception_ptr(std::invalid_argument("Empty futures vector"))
148 );
149 return promise.get_future();
150 }
151
152 auto promise = std::make_shared<std::promise<T>>();
153 auto result_future = promise->get_future();
154 auto completed = std::make_shared<std::atomic<bool>>(false);
155 auto futures_ptr = std::make_shared<std::vector<std::future<T>>>(std::move(futures));
156
157 // Launch threads for each future
158 for (std::size_t i = 0; i < futures_ptr->size(); ++i) {
159 std::thread([promise, completed, futures_ptr, i]() {
160 try {
161 auto& future = (*futures_ptr)[i];
162 T result = future.get();
163
164 bool expected = false;
165 if (completed->compare_exchange_strong(expected, true)) {
166 promise->set_value(std::move(result));
167 }
168 } catch (...) {
169 bool expected = false;
170 if (completed->compare_exchange_strong(expected, true)) {
171 promise->set_exception(std::current_exception());
172 }
173 }
174 }).detach();
175 }
176
177 return result_future;
178}
@ completed
Job has completed successfully.

References completed.

◆ when_any() [2/2]

auto kcenon::thread::when_any ( std::vector< std::future< void > > && futures) -> std::future<void>
inline

Specialization of when_any for void futures.

Definition at line 183 of file when_helpers.h.

185{
186 if (futures.empty()) {
187 std::promise<void> promise;
188 promise.set_exception(
189 std::make_exception_ptr(std::invalid_argument("Empty futures vector"))
190 );
191 return promise.get_future();
192 }
193
194 auto promise = std::make_shared<std::promise<void>>();
195 auto result_future = promise->get_future();
196 auto completed = std::make_shared<std::atomic<bool>>(false);
197 auto futures_ptr = std::make_shared<std::vector<std::future<void>>>(std::move(futures));
198
199 for (std::size_t i = 0; i < futures_ptr->size(); ++i) {
200 std::thread([promise, completed, futures_ptr, i]() {
201 try {
202 (*futures_ptr)[i].get();
203
204 bool expected = false;
205 if (completed->compare_exchange_strong(expected, true)) {
206 promise->set_value();
207 }
208 } catch (...) {
209 bool expected = false;
210 if (completed->compare_exchange_strong(expected, true)) {
211 promise->set_exception(std::current_exception());
212 }
213 }
214 }).detach();
215 }
216
217 return result_future;
218}

References completed.

◆ when_any_with_index()

template<typename T >
auto kcenon::thread::when_any_with_index ( std::vector< std::future< T > > && futures) -> std::future<std::pair<std::size_t, T>>

Wait for any future to complete with index.

Template Parameters
TThe common result type of all futures
Parameters
futuresVector of futures
Returns
A future containing a pair of (index, value) for the first completed

Similar to when_any, but also returns the index of which future completed first.

Usage Example

std::vector<std::future<int>> futures;
futures.push_back(pool->submit_async([]{ return fetch_from_server_a(); }));
futures.push_back(pool->submit_async([]{ return fetch_from_server_b(); }));
auto first = when_any_with_index(std::move(futures));
auto [idx, result] = first.get(); // idx = which completed, result = value
auto when_any_with_index(std::vector< std::future< T > > &&futures) -> std::future< std::pair< std::size_t, T > >
Wait for any future to complete with index.

Definition at line 240 of file when_helpers.h.

242{
243 if (futures.empty()) {
244 std::promise<std::pair<std::size_t, T>> promise;
245 promise.set_exception(
246 std::make_exception_ptr(std::invalid_argument("Empty futures vector"))
247 );
248 return promise.get_future();
249 }
250
251 auto promise = std::make_shared<std::promise<std::pair<std::size_t, T>>>();
252 auto result_future = promise->get_future();
253 auto completed = std::make_shared<std::atomic<bool>>(false);
254 auto futures_ptr = std::make_shared<std::vector<std::future<T>>>(std::move(futures));
255
256 for (std::size_t i = 0; i < futures_ptr->size(); ++i) {
257 std::thread([promise, completed, futures_ptr, i]() {
258 try {
259 auto& future = (*futures_ptr)[i];
260 T result = future.get();
261
262 bool expected = false;
263 if (completed->compare_exchange_strong(expected, true)) {
264 promise->set_value(std::make_pair(i, std::move(result)));
265 }
266 } catch (...) {
267 bool expected = false;
268 if (completed->compare_exchange_strong(expected, true)) {
269 promise->set_exception(std::current_exception());
270 }
271 }
272 }).detach();
273 }
274
275 return result_future;
276}

References completed.

Variable Documentation

◆ has_blocking_overflow_v

template<typename T >
bool kcenon::thread::has_blocking_overflow_v = has_blocking_overflow<T>::value
constexpr

Definition at line 266 of file queue_traits.h.

◆ INVALID_JOB_ID

◆ is_bound_policy_v

template<typename T >
bool kcenon::thread::is_bound_policy_v = detail::has_bound_policy_tag<T>::value
constexpr

Check if type is a bound policy.

Definition at line 82 of file queue_traits.h.

Referenced by kcenon::thread::queue_factory::create_custom_policy_queue().

◆ is_bounded_queue_v

template<typename T >
bool kcenon::thread::is_bounded_queue_v = is_bounded_queue<T>::value
constexpr

Definition at line 250 of file queue_traits.h.

◆ is_lockfree_queue_v

template<typename T >
bool kcenon::thread::is_lockfree_queue_v = is_lockfree_queue<T>::value
constexpr

Definition at line 232 of file queue_traits.h.

◆ is_overflow_policy_v

template<typename T >
bool kcenon::thread::is_overflow_policy_v = detail::has_overflow_policy_tag<T>::value
constexpr

Check if type is an overflow policy.

Definition at line 88 of file queue_traits.h.

Referenced by kcenon::thread::queue_factory::create_custom_policy_queue().

◆ is_policy_queue_v

template<typename T >
bool kcenon::thread::is_policy_queue_v = detail::is_policy_queue_impl<std::remove_cv_t<T>>::value
constexpr

Check if type is a policy_queue instantiation.

This trait identifies whether a type is an instantiation of the policy_queue template, allowing compile-time branching based on queue type.

Usage Example

template<typename Queue>
void process_queue(Queue& q) {
if constexpr (is_policy_queue_v<Queue>) {
// Access policy-specific features
auto caps = q.get_capabilities();
}
}
constexpr bool is_policy_queue_v
Check if type is a policy_queue instantiation.

Definition at line 159 of file queue_traits.h.

◆ is_queue_capabilities_v

template<typename T >
bool kcenon::thread::is_queue_capabilities_v
constexpr
Initial value:
=
std::is_base_of_v<queue_capabilities_interface, std::remove_cv_t<T>>

Check if type is a queue_capabilities_interface.

Definition at line 173 of file queue_traits.h.

◆ is_scheduler_v

template<typename T >
bool kcenon::thread::is_scheduler_v = std::is_base_of_v<scheduler_interface, std::remove_cv_t<T>>
constexpr

Check if type is a scheduler_interface.

Detects whether a type inherits from scheduler_interface.

Definition at line 167 of file queue_traits.h.

◆ is_sync_policy_v

template<typename T >
bool kcenon::thread::is_sync_policy_v = detail::has_sync_policy_tag<T>::value
constexpr

Check if type is a sync policy.

Definition at line 76 of file queue_traits.h.

Referenced by kcenon::thread::queue_factory::create_custom_policy_queue().