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

A foundational class for implementing custom worker threads. More...

#include <thread_base.h>

Inheritance diagram for kcenon::thread::thread_base:
Inheritance graph
Collaboration diagram for kcenon::thread::thread_base:
Collaboration graph

Public Member Functions

 thread_base (const thread_base &)=delete
 
thread_baseoperator= (const thread_base &)=delete
 
 thread_base (thread_base &&)=delete
 
thread_baseoperator= (thread_base &&)=delete
 
 thread_base (const std::string &thread_title="thread_base")
 Constructs a new thread_base object.
 
virtual ~thread_base (void)
 Virtual destructor. Ensures proper cleanup of derived classes.
 
auto set_wake_interval (const std::optional< std::chrono::milliseconds > &wake_interval) -> void
 Sets the interval at which the worker thread should wake up (if any).
 
auto get_wake_interval () const -> std::optional< std::chrono::milliseconds >
 Gets the current wake interval setting.
 
auto start (void) -> common::VoidResult
 Starts the worker thread.
 
auto stop (void) -> common::VoidResult
 Requests the worker thread to stop and waits for it to finish.
 
auto get_thread_title () const -> std::string
 Returns the worker thread's title.
 
auto is_running () const -> bool
 Checks whether the worker thread is currently running.
 
auto get_thread_id () const -> std::thread::id
 Gets the native thread ID of the worker thread.
 
virtual auto to_string (void) const -> std::string
 Returns a string representation of this thread_base object.
 

Protected Member Functions

virtual auto should_continue_work (void) const -> bool
 Determines whether the thread should continue doing work.
 
virtual auto before_start (void) -> common::VoidResult
 Called just before the worker thread starts running.
 
virtual auto do_work (void) -> common::VoidResult
 The main work routine for the worker thread.
 
virtual auto after_stop (void) -> common::VoidResult
 Called immediately after the worker thread has stopped.
 
virtual auto on_stop_requested (void) -> void
 Called when stop() is requested, before the thread actually stops.
 

Protected Attributes

std::optional< std::chrono::milliseconds > wake_interval_
 Interval at which the thread is optionally awakened.
 

Private Attributes

std::atomic< int > consecutive_failures_ {0}
 Counter for consecutive failures in do_work() execution.
 
std::mutex wake_interval_mutex_
 Mutex for synchronizing access to the wake_interval_ member.
 
lifecycle_controller lifecycle_
 Lifecycle controller managing thread state and synchronization.
 
std::unique_ptr< std::thread > worker_thread_
 A std::thread for managing the worker thread's lifecycle (legacy mode).
 
std::string thread_title_
 A string title for identifying or naming the worker thread.
 

Static Private Attributes

static constexpr int max_consecutive_failures = 10
 Maximum number of consecutive failures before stopping the thread.
 

Detailed Description

A foundational class for implementing custom worker threads.

The thread_base class provides a framework for managing a single worker thread, offering lifecycle methods (start, stop), optional wake intervals, and hooks (before_start, do_work, after_stop) for derived classes to customize behavior.

This class abstracts platform-specific thread management details and provides a unified interface for both C++20 std::jthread and traditional std::thread, selected at compile time via the USE_STD_JTHREAD macro.

Key Features

  • Standardized thread lifecycle management (start/stop)
  • Thread condition monitoring
  • Customizable worker behavior through virtual method overrides
  • Optional periodic wake intervals for recurring tasks
  • Built-in cancellation support (via std::jthread or custom mechanism)
  • Thread-safe signaling and state management

Thread Safety

All public methods in thread_base are thread-safe. The class uses internal synchronization mechanisms to protect its state.

Typical Usage

  1. Inherit from thread_base and override do_work(), before_start(), and/or after_stop() as needed.
  2. Instantiate your derived class, set a wake interval if desired, then call start() to launch the thread.
  3. When shutting down or no longer needing the thread's work, call stop().
  4. The thread can periodically check should_continue_work() or internal conditions to determine if it should continue running.

Example

class my_worker : public thread_base {
public:
my_worker() : thread_base("my_worker") {}
protected:
common::VoidResult before_start() override {
// Initialize resources
return common::ok();
}
common::VoidResult do_work() override {
// Perform work
return common::ok();
}
common::VoidResult after_stop() override {
// Clean up resources
return common::ok();
}
};
int main() {
auto worker = std::make_unique<my_worker>();
worker->set_wake_interval(std::chrono::milliseconds(100)); // Wake every 100ms
auto result = worker->start();
// Do other work...
worker->stop();
return 0;
}
A foundational class for implementing custom worker threads.
virtual auto do_work(void) -> common::VoidResult
The main work routine for the worker thread.
virtual auto after_stop(void) -> common::VoidResult
Called immediately after the worker thread has stopped.
virtual auto before_start(void) -> common::VoidResult
Called just before the worker thread starts running.
See also
kcenon::thread::job For the work unit class processed by workers
kcenon::thread::job_queue For the thread-safe queue used with workers
kcenon::thread::thread_worker For a specialized worker implementation

Definition at line 141 of file thread_base.h.

Constructor & Destructor Documentation

◆ thread_base() [1/3]

kcenon::thread::thread_base::thread_base ( const thread_base & )
delete

◆ thread_base() [2/3]

kcenon::thread::thread_base::thread_base ( thread_base && )
delete

◆ thread_base() [3/3]

kcenon::thread::thread_base::thread_base ( const std::string & thread_title = "thread_base")

Constructs a new thread_base object.

Constructs a new thread_base instance with the specified title.

Parameters
thread_titleA human-readable title for this worker thread (default: "thread_base").

The thread_title can be useful for logging, debugging, or thread naming (where the platform supports it).

Implementation details:

  • Initializes the worker_thread_ pointer to nullptr (thread not started)
  • lifecycle_controller handles stop control and state management
  • Sets wake_interval_ to std::nullopt (no periodic wake-ups by default)
  • Sets thread_title_ to the provided title

Definition at line 27 of file thread_base.cpp.

28 : wake_interval_(std::nullopt)
29 , lifecycle_()
30 , worker_thread_(nullptr)
31 , thread_title_(thread_title)
32 {
33 }
std::unique_ptr< std::thread > worker_thread_
A std::thread for managing the worker thread's lifecycle (legacy mode).
std::optional< std::chrono::milliseconds > wake_interval_
Interval at which the thread is optionally awakened.
lifecycle_controller lifecycle_
Lifecycle controller managing thread state and synchronization.
std::string thread_title_
A string title for identifying or naming the worker thread.

◆ ~thread_base()

kcenon::thread::thread_base::~thread_base ( void )
virtual

Virtual destructor. Ensures proper cleanup of derived classes.

Destroys the thread_base instance, stopping the thread if needed.

If the thread is still running when the destructor is called, stop() is typically called internally to join the thread before destruction.

Implementation details:

  • Calls stop() to ensure the thread is properly terminated
  • The stop() method handles joining the thread and cleaning up resources
  • This ensures no thread resources are leaked when the object is destroyed
Note
This destructor is virtual, allowing derived classes to perform their own cleanup operations in their destructors.

Definition at line 46 of file thread_base.cpp.

46{ stop(); }
auto stop(void) -> common::VoidResult
Requests the worker thread to stop and waits for it to finish.

References stop().

Here is the call graph for this function:

Member Function Documentation

◆ after_stop()

virtual auto kcenon::thread::thread_base::after_stop ( void ) -> common::VoidResult
inlineprotectedvirtual

Called immediately after the worker thread has stopped.

Returns
common::VoidResult containing an error on failure, or success value if successful.

Override this method in derived classes to perform any cleanup or finalization tasks once the worker thread has fully exited.

Definition at line 283 of file thread_base.h.

283{ return common::ok(); }

◆ before_start()

virtual auto kcenon::thread::thread_base::before_start ( void ) -> common::VoidResult
inlineprotectedvirtual

Called just before the worker thread starts running.

Returns
common::VoidResult containing an error on failure, or success value if successful.

Override this method in derived classes to perform any initialization or setup required before the worker thread begins its main loop.

Definition at line 264 of file thread_base.h.

264{ return common::ok(); }

◆ do_work()

virtual auto kcenon::thread::thread_base::do_work ( void ) -> common::VoidResult
inlineprotectedvirtual

The main work routine for the worker thread.

Returns
common::VoidResult containing an error on failure, or success value if successful.

Derived classes should override this method to implement the actual work the thread needs to perform. This method is called repeatedly (in an internal loop) until the thread is signaled to stop or should_continue_work() returns false.

Reimplemented in kcenon::thread::thread_worker, kcenon::thread::typed_thread_worker_t< job_type >, and kcenon::thread::typed_thread_worker_t< job_types >.

Definition at line 274 of file thread_base.h.

274{ return common::ok(); }

◆ get_thread_id()

auto kcenon::thread::thread_base::get_thread_id ( ) const -> std::thread::id
nodiscard

Gets the native thread ID of the worker thread.

Returns
The std::thread::id of the worker thread, or default-constructed id if the thread is not running.

Thread Safety:

  • Safe to call from any thread
  • Returns valid ID only when thread is running

Implementation details:

  • Returns the std::thread::id from the underlying thread object
  • Returns default-constructed (empty) id if thread is not running
  • Thread-safe as worker_thread_ pointer is only modified in start()/stop()
Returns
The std::thread::id of the worker thread

Definition at line 355 of file thread_base.cpp.

356 {
357 if (worker_thread_ && worker_thread_->joinable())
358 {
359 return worker_thread_->get_id();
360 }
361 return std::thread::id{};
362 }

References worker_thread_.

◆ get_thread_title()

auto kcenon::thread::thread_base::get_thread_title ( ) const -> std::string
inlinenodiscard

Returns the worker thread's title.

Returns
A string representing the thread's title.

Definition at line 215 of file thread_base.h.

215{ return thread_title_; }

References thread_title_.

◆ get_wake_interval()

auto kcenon::thread::thread_base::get_wake_interval ( ) const -> std::optional<std::chrono::milliseconds>
nodiscard

Gets the current wake interval setting.

Returns
The wake interval if set, or std::nullopt if periodic wake-ups are disabled.
Note
This method is thread-safe.

Implementation details:

  • Uses the same mutex as set_wake_interval() for consistency
  • Returns a copy of the current wake_interval_ value
  • std::nullopt indicates no periodic wake-ups are configured

Thread Safety:

  • Safe to call from any thread concurrently with set_wake_interval()
  • The mutex ensures consistent reads even during concurrent modifications
Returns
Current wake interval or std::nullopt if disabled

Definition at line 83 of file thread_base.cpp.

85 {
86 // Thread-safe read of wake_interval
87 std::scoped_lock<std::mutex> lock(wake_interval_mutex_);
88 return wake_interval_;
89 }
std::mutex wake_interval_mutex_
Mutex for synchronizing access to the wake_interval_ member.

References wake_interval_, and wake_interval_mutex_.

◆ is_running()

auto kcenon::thread::thread_base::is_running ( void ) const -> bool
nodiscard

Checks whether the worker thread is currently running.

Checks if the worker thread is currently active.

Returns
true if the thread is running, false otherwise.

This depends on the thread's internal condition state (e.g., thread_conditions::running).

Implementation details:

  • Uses lifecycle_controller for state checking
  • Considers both Working and Waiting states as "running"
  • Thread-safe operation
Returns
true if thread is actively running (Working or Waiting)

Definition at line 324 of file thread_base.cpp.

325 {
326 return lifecycle_.is_running();
327 }
auto is_running() const noexcept -> bool
Checks if the thread is currently running.

◆ on_stop_requested()

virtual auto kcenon::thread::thread_base::on_stop_requested ( void ) -> void
inlineprotectedvirtual

Called when stop() is requested, before the thread actually stops.

This hook allows derived classes to perform cancellation-related operations, such as signaling running jobs to cancel. This is called from the thread requesting the stop (not from the worker thread itself).

The default implementation does nothing. Override this to propagate cancellation signals to any active work items.

Thread Safety:

  • Called from the thread calling stop()
  • May be called concurrently with do_work()
  • Implementations must be thread-safe
Note
This is called after the stop flag is set but before joining the thread

Reimplemented in kcenon::thread::thread_worker.

Definition at line 302 of file thread_base.h.

302{}

◆ operator=() [1/2]

thread_base & kcenon::thread::thread_base::operator= ( const thread_base & )
delete

◆ operator=() [2/2]

thread_base & kcenon::thread::thread_base::operator= ( thread_base && )
delete

◆ set_wake_interval()

auto kcenon::thread::thread_base::set_wake_interval ( const std::optional< std::chrono::milliseconds > & wake_interval) -> void

Sets the interval at which the worker thread should wake up (if any).

Sets the wake interval for periodic thread wake-ups.

Parameters
wake_intervalDuration in milliseconds for periodic wake-ups, or std::nullopt to disable periodic wake-ups.

If a wake interval is set, the worker thread can periodically perform some action (e.g., housekeeping tasks) even if there's no immediate external signal.

Note
This method is thread-safe.

Implementation details:

  • Uses a dedicated mutex (wake_interval_mutex_) to ensure thread-safe access
  • The scoped_lock ensures automatic release when the function exits
  • This interval controls how often the thread wakes up even when idle
  • Setting std::nullopt disables periodic wake-ups (thread only wakes on signals)

Thread Safety:

  • Safe to call from any thread while the worker thread is running
  • The wake_interval_mutex_ protects against data races with get_wake_interval()

Definition at line 61 of file thread_base.cpp.

63 {
64 // Use dedicated mutex for wake_interval to prevent data races
65 std::scoped_lock<std::mutex> lock(wake_interval_mutex_);
66 wake_interval_ = wake_interval;
67 }

◆ should_continue_work()

virtual auto kcenon::thread::thread_base::should_continue_work ( void ) const -> bool
inlinenodiscardprotectedvirtual

Determines whether the thread should continue doing work.

Returns
true if there is work to do, false otherwise.

The default implementation always returns false (indicating no ongoing work). Override this in derived classes if you wish the thread to perform repeated tasks until some condition changes.

Reimplemented in kcenon::thread::thread_worker, kcenon::thread::typed_thread_worker_t< job_type >, and kcenon::thread::typed_thread_worker_t< job_types >.

Definition at line 255 of file thread_base.h.

255{ return false; }

◆ start()

auto kcenon::thread::thread_base::start ( void ) -> common::VoidResult

Starts the worker thread.

Starts the worker thread and begins execution loop.

Returns
common::VoidResult containing an error on failure, or success value if successful.

Internally, this method:

  1. Calls before_start() to allow derived classes to perform setup.
  2. Spawns a new thread (using either std::jthread or std::thread).
  3. Repeatedly calls do_work() until the thread is signaled to stop.

Implementation details:

  • First checks if thread is already running via lifecycle_controller
  • Calls stop() first to ensure clean state (idempotent operation)
  • Initializes lifecycle_controller for the new thread
  • Creates worker thread that executes the main work loop

Main Work Loop Logic:

  1. Calls before_start() hook for derived class initialization
  2. Enters main loop while not stopped and has work to do
  3. Uses lifecycle_controller for state and wait management
  4. Calls do_work() hook for actual work execution
  5. Handles exceptions from do_work() gracefully
  6. Calls after_stop() hook for cleanup when exiting
Returns
Empty result on success, error on failure

Definition at line 110 of file thread_base.cpp.

111 {
112 // Check if thread is already running using lifecycle_controller
114 {
115 return common::error_info{static_cast<int>(error_code::thread_already_running), "thread is already running", "thread_system"};
116 }
117
118 // Ensure clean state by stopping any existing thread first
119 stop();
120
121 // Initialize lifecycle controller for the new thread
123
124 try
125 {
126 // Create the worker thread using platform-appropriate thread type
127#ifdef USE_STD_JTHREAD
128 worker_thread_ = std::make_unique<std::jthread>(
129#else
130 worker_thread_ = std::make_unique<std::thread>(
131#endif
132 [this](void) // Capture 'this' to access member functions and variables
133 {
134 // Phase 1: Call derived class initialization hook
135 auto work_result = before_start();
136 if (work_result.is_err())
137 {
138 std::cerr << "error before start: " << work_result.error().message
139 << std::endl;
140 }
141
142 // Phase 2: Main work loop - continues until stop requested and no more work
144 {
145 // Update thread state to indicate it's waiting for work
147
148 // Get current wake interval with thread-safe access
149 auto interval = get_wake_interval();
150
151 // Use lifecycle_controller for condition variable operations
152 auto lock = lifecycle_.acquire_lock();
153
154 // Wait strategy depends on whether wake interval is configured
155 if (interval.has_value())
156 {
157 // Timed wait: wake up after interval OR when condition is met
158 lifecycle_.wait_for(lock, interval.value(),
159 [this]() { return should_continue_work(); });
160 }
161 else
162 {
163 // Indefinite wait: only wake up when condition is met
164 lifecycle_.wait(lock,
165 [this]() { return should_continue_work(); });
166 }
167
168 // Check if we should exit the loop
170 {
171 // Update state to indicate graceful shutdown in progress
173 break;
174 }
175
176 // Execute the actual work with exception protection
177 try
178 {
179 // Update state to indicate active work is being performed
181
182 // Call derived class work implementation
183 work_result = do_work();
184 if (work_result.is_err())
185 {
186 // Use structured logger instead of raw std::cerr
190 "Work execution failed",
191 work_result.error().message);
192 }
193
194 // Reset consecutive failures counter on successful completion
195 consecutive_failures_.store(0, std::memory_order_relaxed);
196 }
197 catch (const std::exception& e)
198 {
199 // Track consecutive failures to prevent infinite error loops
200 int failures = consecutive_failures_.fetch_add(1, std::memory_order_relaxed) + 1;
201
205 "Unhandled exception in worker thread (failure " + std::to_string(failures) + ")",
206 e.what());
207
208 // Stop thread if too many consecutive failures occur
209 if (failures >= max_consecutive_failures)
210 {
214 "Too many consecutive failures, stopping thread",
215 "");
216 break; // Exit the main loop
217 }
218
219 // Exponential backoff: 100ms, 200ms, 400ms, ..., max 10 seconds
220 // This prevents CPU spinning and log flooding while giving time for transient issues to resolve
221 auto backoff_ms = std::min(100 * (1 << std::min(failures - 1, 10)), 10000);
222 std::this_thread::sleep_for(std::chrono::milliseconds(backoff_ms));
223 }
224 }
225
226 // Phase 3: Call derived class cleanup hook after main loop exits
227 work_result = after_stop();
228 if (work_result.is_err())
229 {
233 "Error during cleanup",
234 work_result.error().message);
235 }
236 }); // End of lambda function passed to thread constructor
237 }
238 catch (const std::bad_alloc& e)
239 {
240 // Exception-safe cleanup: reset all resources if thread creation fails
242 worker_thread_.reset();
243
244 return common::error_info{static_cast<int>(error_code::resource_allocation_failed), e.what(), "thread_system"};
245 }
246
247 // Thread creation successful
248 return common::ok();
249 }
auto wait(std::unique_lock< std::mutex > &lock, Predicate pred) -> void
Waits on the condition variable with a predicate.
auto is_stop_requested() const noexcept -> bool
Checks if a stop has been requested.
auto set_state(thread_conditions state) noexcept -> void
Sets the thread condition/state.
auto wait_for(std::unique_lock< std::mutex > &lock, const std::chrono::duration< Rep, Period > &timeout, Predicate pred) -> bool
Waits on the condition variable with a timeout and predicate.
auto has_active_source() const noexcept -> bool
Checks if the controller has an active stop source (C++20 only).
auto initialize_for_start() -> void
Initializes the controller for a new thread start.
auto acquire_lock() -> std::unique_lock< std::mutex >
Acquires a unique lock on the condition variable mutex.
auto reset_stop_source() noexcept -> void
Resets the stop control mechanism after thread completion.
static constexpr int max_consecutive_failures
Maximum number of consecutive failures before stopping the thread.
std::atomic< int > consecutive_failures_
Counter for consecutive failures in do_work() execution.
auto get_wake_interval() const -> std::optional< std::chrono::milliseconds >
Gets the current wake interval setting.
virtual auto should_continue_work(void) const -> bool
Determines whether the thread should continue doing work.
static thread_logger & instance()
Get singleton instance.
void log(log_level level, std::string_view thread_name, std::string_view message, std::string_view context="")
Log a message with context.
@ Waiting
Thread waiting for work or tasks.
@ Stopping
Thread in the process of stopping.
@ Working
Thread currently processing a task.

References kcenon::thread::critical, kcenon::thread::error, kcenon::thread::thread_logger::instance(), kcenon::thread::thread_logger::log(), kcenon::thread::resource_allocation_failed, kcenon::thread::Stopping, kcenon::thread::thread_already_running, kcenon::thread::Waiting, and kcenon::thread::Working.

Here is the call graph for this function:

◆ stop()

auto kcenon::thread::thread_base::stop ( void ) -> common::VoidResult

Requests the worker thread to stop and waits for it to finish.

Stops the worker thread and waits for it to complete.

Returns
common::VoidResult containing an error on failure, or success value if successful.

Internally, this method:

  1. Signals the thread to stop (via stop_source_ or stop_requested_).
  2. Joins the thread, ensuring it has fully exited.
  3. Calls after_stop() for post-shutdown cleanup in derived classes.

Implementation details:

  • This method is idempotent - safe to call multiple times
  • First checks if there's actually a thread to stop
  • Uses lifecycle_controller for stop signaling and state management
  • Notifies condition variable to wake up waiting thread
  • Joins the thread to wait for complete shutdown
  • Cleans up all thread-related resources

Shutdown Sequence:

  1. Signal stop request via lifecycle_controller
  2. Call derived class hook for cancellation propagation
  3. Notify condition variable to wake sleeping thread
  4. Wait for thread to exit its main loop and complete after_stop()
  5. Clean up thread object and reset lifecycle_controller
Returns
Empty result on success, error if thread wasn't running

Definition at line 271 of file thread_base.cpp.

272 {
273 // Early exit if no thread to stop (idempotent behavior)
274 if (worker_thread_ == nullptr)
275 {
276 return common::error_info{static_cast<int>(error_code::thread_not_running), "thread is not running", "thread_system"};
277 }
278
279 // Only attempt to stop if thread is actually joinable
280 if (worker_thread_->joinable())
281 {
282 // Self-stop detection: prevent deadlock if thread tries to stop itself
283 // Calling join() from the same thread would cause deadlock
284 if (worker_thread_->get_id() == std::this_thread::get_id())
285 {
286 return common::error_info{static_cast<int>(error_code::invalid_argument),
287 "cannot stop thread from within itself - would cause deadlock", "thread_system"};
288 }
289
290 // Step 1: Signal the thread to stop via lifecycle_controller
292
293 // Step 1.5: Call derived class hook for cancellation propagation
294 // This allows derived classes (e.g., thread_worker) to cancel running jobs
296
297 // Step 2: Wake up the thread if it's waiting on condition variable
299
300 // Step 3: Wait for the thread to complete its shutdown sequence
301 worker_thread_->join(); // Blocks until thread exits
302 }
303
304 // Step 4: Clean up thread resources
306 worker_thread_.reset(); // Release thread object
307
308 // Step 5: Update thread state to indicate complete shutdown
310
311 return common::ok();
312 }
auto notify_all() -> void
Notifies all waiting threads.
auto request_stop() noexcept -> void
Requests the thread to stop.
auto set_stopped() noexcept -> void
Marks the thread as stopped.
virtual auto on_stop_requested(void) -> void
Called when stop() is requested, before the thread actually stops.

References kcenon::thread::invalid_argument, and kcenon::thread::thread_not_running.

Referenced by ~thread_base().

Here is the caller graph for this function:

◆ to_string()

auto kcenon::thread::thread_base::to_string ( void ) const -> std::string
nodiscardvirtual

Returns a string representation of this thread_base object.

Provides a string representation of the thread's current state.

Returns
A string containing descriptive or diagnostic information about the thread.

Derived classes may override this to include additional details (e.g., current status, counters, or other state).

Implementation details:

  • Uses the formatter utility to create consistent output format
  • Includes both thread title and current condition
  • Useful for logging and debugging purposes
  • Thread-safe via lifecycle_controller
Returns
Formatted string showing thread title and current state

Definition at line 340 of file thread_base.cpp.

341 {
343 }
auto get_state() const noexcept -> thread_conditions
Gets the current thread condition/state.
static auto format(const char *formats, const FormatArgs &... args) -> std::string
Formats a narrow-character string with the given arguments.
Definition formatter.h:129

References utility_module::formatter::format().

Referenced by std::formatter< kcenon::thread::thread_worker >::format(), std::formatter< kcenon::thread::thread_worker, wchar_t >::format(), std::formatter< kcenon::thread::typed_thread_worker_t< job_type > >::format(), and std::formatter< kcenon::thread::typed_thread_worker_t< job_type >, wchar_t >::format().

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

Member Data Documentation

◆ consecutive_failures_

std::atomic<int> kcenon::thread::thread_base::consecutive_failures_ {0}
private

Counter for consecutive failures in do_work() execution.

This counter is incremented each time do_work() throws an exception. It is reset to 0 when do_work() completes successfully. Used to implement exponential backoff and prevent infinite error loops.

Definition at line 323 of file thread_base.h.

323{0};

◆ lifecycle_

lifecycle_controller kcenon::thread::thread_base::lifecycle_
private

Lifecycle controller managing thread state and synchronization.

Consolidates condition variable, mutex, stop request, and state management into a single reusable component.

Definition at line 347 of file thread_base.h.

◆ max_consecutive_failures

int kcenon::thread::thread_base::max_consecutive_failures = 10
staticconstexprprivate

Maximum number of consecutive failures before stopping the thread.

If do_work() throws exceptions this many times in a row, the thread will stop automatically to prevent infinite error loops and resource exhaustion.

Definition at line 331 of file thread_base.h.

◆ thread_title_

std::string kcenon::thread::thread_base::thread_title_
private

A string title for identifying or naming the worker thread.

Definition at line 368 of file thread_base.h.

Referenced by get_thread_title().

◆ wake_interval_

std::optional<std::chrono::milliseconds> kcenon::thread::thread_base::wake_interval_
protected

Interval at which the thread is optionally awakened.

If set, the worker thread can wake periodically (in addition to any other wake conditions) to perform tasks at regular intervals.

Note
Access to this member must be synchronized using wake_interval_mutex_

Definition at line 313 of file thread_base.h.

Referenced by get_wake_interval().

◆ wake_interval_mutex_

std::mutex kcenon::thread::thread_base::wake_interval_mutex_
mutableprivate

Mutex for synchronizing access to the wake_interval_ member.

This mutex must be acquired when reading or writing wake_interval_ to prevent data races between the setter and the worker thread.

Definition at line 339 of file thread_base.h.

Referenced by get_wake_interval().

◆ worker_thread_

std::unique_ptr<std::thread> kcenon::thread::thread_base::worker_thread_
private

A std::thread for managing the worker thread's lifecycle (legacy mode).

If USE_STD_JTHREAD is not defined, we fall back to a standard thread.

Definition at line 362 of file thread_base.h.

Referenced by get_thread_id().


The documentation for this class was generated from the following files: