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

Represents a unit of work (task) to be executed, typically by a job queue. More...

#include <job.h>

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

Public Member Functions

auto get_job_id () const -> std::uint64_t
 Gets the unique ID of this job.
 
auto get_enqueue_time () const -> std::chrono::steady_clock::time_point
 Gets the time when this job was created (enqueued).
 
 job (const std::string &name="job")
 Constructs a new job with an optional human-readable name.
 
 job (const std::vector< uint8_t > &data, const std::string &name="data_job")
 Constructs a new job with associated raw byte data and a name.
 
virtual ~job (void)
 Virtual destructor for the job class to allow proper cleanup in derived classes.
 
auto get_name (void) const -> std::string
 Retrieves the name of this job.
 
virtual auto do_work (void) -> common::VoidResult
 The core task execution method to be overridden by derived classes.
 
virtual auto set_cancellation_token (const cancellation_token &token) -> void
 Sets a cancellation token that can be used to cancel the job.
 
virtual auto get_cancellation_token () const -> cancellation_token
 Gets the cancellation token associated with this job.
 
virtual auto set_job_queue (const std::shared_ptr< job_queue > &job_queue) -> void
 Associates this job with a specific job_queue.
 
virtual auto get_job_queue (void) const -> std::shared_ptr< job_queue >
 Retrieves the job_queue associated with this job, if any.
 
virtual auto to_string (void) const -> std::string
 Provides a string representation of the job for logging or debugging.
 
auto with_on_complete (std::function< void(common::VoidResult)> callback) -> job &
 Attaches a completion callback to this job.
 
auto with_on_error (std::function< void(const common::error_info &)> callback) -> job &
 Attaches an error callback to this job.
 
auto with_priority (job_priority priority) -> job &
 Sets the priority level for this job.
 
auto with_cancellation (const cancellation_token &token) -> job &
 Attaches a cancellation token to this job via composition.
 
auto with_retry (const retry_policy &policy) -> job &
 Attaches a retry policy to this job.
 
auto with_timeout (std::chrono::milliseconds timeout) -> job &
 Sets a timeout for job execution.
 
auto get_priority () const -> job_priority
 Gets the priority level of this job.
 
auto get_retry_policy () const -> std::optional< retry_policy >
 Gets the retry policy of this job.
 
auto get_timeout () const -> std::optional< std::chrono::milliseconds >
 Gets the timeout duration for this job.
 
auto has_explicit_cancellation () const -> bool
 Checks if this job has an explicit cancellation set via composition.
 
auto has_components () const -> bool
 Checks if this job has any composed components.
 

Protected Member Functions

auto invoke_callbacks (const common::VoidResult &result) -> void
 Invokes the completion callbacks if they are set.
 

Protected Attributes

std::string name_
 The descriptive name of the job, used primarily for identification and logging.
 
std::vector< uint8_t > data_
 An optional container of raw byte data that may be used by the job.
 
std::weak_ptr< job_queuejob_queue_
 A weak reference to the job_queue that currently manages this job.
 
cancellation_token cancellation_token_
 The cancellation token associated with this job.
 

Private Member Functions

auto ensure_components () -> job_components &
 Ensures components_ is allocated (lazy initialization).
 

Private Attributes

std::uint64_t job_id_
 Unique identifier for this job.
 
std::chrono::steady_clock::time_point enqueue_time_
 Time when the job was created.
 
std::unique_ptr< job_componentscomponents_
 Composed components for this job.
 

Static Private Attributes

static std::atomic< std::uint64_t > next_job_id_ {0}
 Static counter for generating unique job IDs.
 

Detailed Description

Represents a unit of work (task) to be executed, typically by a job queue.

The job class provides a base interface for scheduling and executing discrete tasks within a multi-threaded environment. Derived classes can override the do_work() method to implement custom logic for their specific tasks.

Thread-Safety

  • do_work() will generally be called from a worker thread. If your task accesses shared data or interacts with shared resources, you must ensure your implementation is thread-safe.
  • The job itself is meant to be used via std::shared_ptr, making it easier to manage lifetimes across multiple threads.

Error Handling

  • A job returns a common::VoidResult from do_work().
    • Returning common::ok() indicates success.
    • Returning a common::error_info indicates failure with a typed error code and message.
  • Error information can be used for logging, debugging, or to retry a job if desired.

Usage Example

// 1. Create a custom job that overrides do_work().
class my_job : public kcenon::thread::job
{
public:
my_job() : job("my_custom_job") {}
common::VoidResult do_work() override
{
// Execute custom logic:
bool success = perform_operation();
if (!success)
return common::error_info{static_cast<int>(error_code::job_execution_failed), "Operation failed in my_custom_job"};
return common::ok(); // success
}
};
// 2. Submit the job to a queue.
auto q = std::make_shared<kcenon::thread::job_queue>();
auto job_ptr = std::make_shared<my_job>();
q->enqueue(job_ptr);
Represents a unit of work (task) to be executed, typically by a job queue.
Definition job.h:136
virtual auto do_work(void) -> common::VoidResult
The core task execution method to be overridden by derived classes.
Definition job.cpp:135
std::shared_ptr< job_interface > job_ptr
Shared pointer type for job objects.
Definition job_types.h:84
Examples
adaptive_queue_sample.cpp, crash_protection/main.cpp, job_cancellation_example.cpp, minimal_thread_pool.cpp, mpmc_queue_sample.cpp, multi_process_monitoring_integration.cpp, queue_factory_sample.cpp, and typed_job_queue_sample.cpp.

Definition at line 135 of file job.h.

Constructor & Destructor Documentation

◆ job() [1/2]

kcenon::thread::job::job ( const std::string & name = "job")

Constructs a new job with an optional human-readable name.

Constructs a basic job with name only.

Use this constructor when your derived job class does not need to store any initial data beyond what you might manually store in derived class members.

Parameters
nameA descriptive name for the job (default is "job").

Example

// Creating a basic job with a custom name
auto my_simple_job = std::make_shared<kcenon::thread::job>("simple_job");

Implementation details:

  • Initializes job with descriptive name for identification
  • Creates empty data vector (no binary data associated)
  • Cancellation token is default-constructed (not cancelled)
  • Job queue is not associated initially (weak_ptr is empty)

Use Cases:

  • Simple computational jobs without input data
  • Lambda-based callback jobs
  • Jobs that generate data rather than process it
Parameters
nameDescriptive name for debugging and logging
Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/job_builder.h, and job_cancellation_example.cpp.

Definition at line 53 of file job.cpp.

54 : name_(name)
55 , data_(std::vector<uint8_t>())
56 , job_id_(next_job_id_.fetch_add(1, std::memory_order_relaxed))
57 , enqueue_time_(std::chrono::steady_clock::now())
58 {
59 }
std::chrono::steady_clock::time_point enqueue_time_
Time when the job was created.
Definition job.h:526
std::vector< uint8_t > data_
An optional container of raw byte data that may be used by the job.
Definition job.h:488
std::string name_
The descriptive name of the job, used primarily for identification and logging.
Definition job.h:480
std::uint64_t job_id_
Unique identifier for this job.
Definition job.h:518
static std::atomic< std::uint64_t > next_job_id_
Static counter for generating unique job IDs.
Definition job.h:510

◆ job() [2/2]

kcenon::thread::job::job ( const std::vector< uint8_t > & data,
const std::string & name = "data_job" )

Constructs a new job with associated raw byte data and a name.

Constructs a data-processing job with binary data.

This constructor is particularly useful if your job needs an inline payload or associated data that should be passed directly to do_work().

Parameters
dataA vector of bytes serving as the job's payload.
nameA descriptive name for the job (default is "data_job").

Example

// Creating a job that has binary data.
std::vector<uint8_t> my_data = {0xDE, 0xAD, 0xBE, 0xEF};
auto data_job = std::make_shared<kcenon::thread::job>(my_data, "data_handling_job");

Implementation details:

  • Stores binary data for processing during job execution
  • Data is copied into the job (caller retains ownership of original)
  • Suitable for file processing, network data handling, etc.
  • Memory efficient for moderate data sizes

Data Handling:

  • Data is stored as std::vector<uint8_t> for flexibility
  • Supports any binary data format (images, documents, network packets)
  • Data lifetime matches job lifetime (automatic cleanup)

Performance Considerations:

  • Data is copied during construction (consider move semantics for large data)
  • Memory usage scales with data size
  • Efficient for data sizes up to several MB
Parameters
dataBinary data to be processed by this job
nameDescriptive name for debugging and logging

Definition at line 83 of file job.cpp.

84 : name_(name)
85 , data_(data)
86 , job_id_(next_job_id_.fetch_add(1, std::memory_order_relaxed))
87 , enqueue_time_(std::chrono::steady_clock::now())
88 {
89 }

◆ ~job()

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

Virtual destructor for the job class to allow proper cleanup in derived classes.

Destroys the job and cleans up resources.

Implementation details:

  • Virtual destructor ensures proper cleanup of derived classes
  • Automatically cleans up stored data and job queue reference
  • No manual cleanup required due to RAII design
  • Safe to destroy even if job is queued (weak_ptr prevents dangling references)

Definition at line 100 of file job.cpp.

100{}

Member Function Documentation

◆ do_work()

auto kcenon::thread::job::do_work ( void ) -> common::VoidResult
nodiscardvirtual

The core task execution method to be overridden by derived classes.

Default implementation of work execution (must be overridden).

Returns
A common::VoidResult indicating success or error:
  • A success result (constructed with common::ok()) if no error occurred.
  • An error result (constructed with common::error_info{code, message}) on failure.

Default Behavior

The base class implementation simply returns a success result. Override this method in a derived class to perform meaningful work.

Concurrency

  • Typically invoked by worker threads in a job_queue.
  • Ensure that any shared data or resources accessed here are protected with appropriate synchronization mechanisms (mutexes, locks, etc.) if needed.
  • This method should check the cancellation token if one is set and return an error with code operation_canceled if the token is cancelled.

Implementation details:

  • Base implementation always returns "not implemented" error
  • Forces derived classes to provide actual work implementation
  • Maintains compatibility with result_void error handling
  • Should never be called in production (indicates missing override)

Design Pattern:

  • Template method pattern: defines interface, requires implementation
  • Pure virtual in spirit (returns error instead of being pure virtual)
  • Enables compilation while encouraging proper inheritance

Derived Class Requirements:

  • Must override this method to provide actual work logic
  • Should return common::ok() on success
  • Should return common::error_info{...} on failure with descriptive message
Returns
Error indicating method needs to be implemented in derived class

Reimplemented in cancellable_long_job, kcenon::thread::aging_typed_job_t< job_type >, kcenon::thread::aging_typed_job_t< job_types >, kcenon::thread::callback_job, kcenon::thread::callback_typed_job_t< job_type >, kcenon::thread::dag_job, kcenon::thread::future_job< R >, kcenon::thread::job_builder::built_job, kcenon::thread::protected_job, and non_cancellable_job.

Examples
adaptive_queue_sample.cpp, mpmc_queue_sample.cpp, and typed_job_queue_sample.cpp.

Definition at line 135 of file job.cpp.

135 {
136 // Base implementation indicates missing override in derived class
137 // This should never be called in production code
138 return common::error_info{static_cast<int>(error_code::not_implemented), "job::do_work() must be implemented in derived class", "thread_system"};
139 }

References kcenon::thread::not_implemented.

Referenced by basic_spsc_example(), basic_typed_queue_example(), batch_operations_example(), kcenon::thread::callback_job::do_work(), kcenon::thread::typed_thread_worker_t< job_type >::do_work(), mpmc_example(), mpmc_typed_queue_example(), performance_comparison_example(), policy_comparison_example(), and stress_test_example().

Here is the caller graph for this function:

◆ ensure_components()

auto kcenon::thread::job::ensure_components ( ) -> job_components&
private

Ensures components_ is allocated (lazy initialization).

Ensures the components structure is allocated.

Implementation details:

  • Lazy initialization: only allocates memory when first needed
  • Returns reference for convenient access after ensuring allocation
  • Thread-safety note: this method is not thread-safe, but composition is typically done during job construction before submission to a queue
Returns
Reference to the components structure

Definition at line 279 of file job.cpp.

280 {
281 if (!components_)
282 {
283 components_ = std::make_unique<job_components>();
284 }
285 return *components_;
286 }
std::unique_ptr< job_components > components_
Composed components for this job.
Definition job.h:535

◆ get_cancellation_token()

auto kcenon::thread::job::get_cancellation_token ( ) const -> cancellation_token
nodiscardvirtual

Gets the cancellation token associated with this job.

Gets the current cancellation token.

Returns
The cancellation token, or a default token if none was set.

Implementation details:

  • Returns copy of stored cancellation token
  • Thread-safe operation (cancellation_token is thread-safe)
  • Used by derived classes to check cancellation status
  • Returns default token if none was set (not cancelled)

Typical Usage in Derived Classes:

auto do_work() -> result_void {
auto token = get_cancellation_token();
for (int i = 0; i < large_number; ++i) {
if (token.is_cancelled()) {
return error{error_code::cancelled, "Job was cancelled"};
}
// Do work...
}
return {};
}
Represents an error in the thread system.
virtual auto get_cancellation_token() const -> cancellation_token
Gets the cancellation token associated with this job.
Definition job.cpp:192
Wrapper for void result.
Returns
Current cancellation token

Definition at line 192 of file job.cpp.

192 {
193 return cancellation_token_;
194 }
cancellation_token cancellation_token_
The cancellation token associated with this job.
Definition job.h:504

References cancellation_token_.

◆ get_enqueue_time()

auto kcenon::thread::job::get_enqueue_time ( ) const -> std::chrono::steady_clock::time_point
inlinenodiscard

Gets the time when this job was created (enqueued).

Returns
Time point when the job was created.

Definition at line 151 of file job.h.

152 {
153 return enqueue_time_;
154 }

References enqueue_time_.

◆ get_job_id()

auto kcenon::thread::job::get_job_id ( ) const -> std::uint64_t
inlinenodiscard

Gets the unique ID of this job.

Returns
The unique job identifier.

Thread Safety:

  • Safe to call from any thread (ID is immutable after construction)

Definition at line 145 of file job.h.

145{ return job_id_; }

References job_id_.

◆ get_job_queue()

auto kcenon::thread::job::get_job_queue ( void ) const -> std::shared_ptr<job_queue>
nodiscardvirtual

Retrieves the job_queue associated with this job, if any.

Gets the associated job queue if it still exists.

Returns
A std::shared_ptr to the associated job_queue. Will be empty if no queue was set or if the queue has already been destroyed.

Usage Example

auto jq = get_job_queue();
if (jq)
{
// Safe to use jq here
}
else
{
// The queue is no longer valid
}
virtual auto get_job_queue(void) const -> std::shared_ptr< job_queue >
Retrieves the job_queue associated with this job, if any.
Definition job.cpp:244

Implementation details:

  • Converts weak_ptr to shared_ptr (may return nullptr)
  • Thread-safe operation (weak_ptr::lock is atomic)
  • Returns nullptr if queue has been destroyed
  • Used for advanced job scheduling scenarios

Return Value Interpretation:

  • Valid shared_ptr: Queue is alive and accessible
  • nullptr: Queue has been destroyed or was never set

Safety Considerations:

  • Always check return value before use
  • Queue may be destroyed between check and use
  • Designed to fail gracefully if queue is unavailable
Returns
Shared pointer to job queue or nullptr if unavailable

Definition at line 244 of file job.cpp.

244{ return job_queue_.lock(); }
std::weak_ptr< job_queue > job_queue_
A weak reference to the job_queue that currently manages this job.
Definition job.h:496

◆ get_name()

auto kcenon::thread::job::get_name ( void ) const -> std::string
nodiscard

Retrieves the name of this job.

Gets the descriptive name of this job.

Returns
A string containing the name assigned to this job.

The name can be useful for logging and diagnostic messages, especially when multiple jobs are running concurrently.

Implementation details:

  • Simple accessor for job identification
  • Thread-safe (string is immutable after construction)
  • Used for debugging, logging, and diagnostics
Returns
Job name as provided during construction
Examples
job_cancellation_example.cpp.

Definition at line 112 of file job.cpp.

112{ return name_; }

Referenced by cancellable_long_job::do_work(), non_cancellable_job::do_work(), kcenon::thread::dag_job::get_info(), kcenon::thread::protected_job::get_name(), kcenon::thread::dag_scheduler::to_dot(), and kcenon::thread::dag_job::to_string().

Here is the caller graph for this function:

◆ get_priority()

auto kcenon::thread::job::get_priority ( ) const -> job_priority
nodiscard

Gets the priority level of this job.

Returns
The job's priority, or job_priority::normal if not set

Implementation details:

  • Returns normal priority if not explicitly set
  • Returns the composed priority if set via with_priority()
Returns
The job's priority level

Definition at line 400 of file job.cpp.

401 {
402 if (components_ && components_->priority.has_value())
403 {
404 return components_->priority.value();
405 }
407 }
@ normal
Normal priority, default for most jobs.

References components_, and kcenon::thread::normal.

◆ get_retry_policy()

auto kcenon::thread::job::get_retry_policy ( ) const -> std::optional<retry_policy>
nodiscard

Gets the retry policy of this job.

Returns
The job's retry policy, or std::nullopt if not set

Implementation details:

  • Returns the retry policy if set via with_retry()
  • Returns std::nullopt if no retry policy was configured
Returns
The job's retry policy or std::nullopt

Definition at line 418 of file job.cpp.

419 {
420 if (components_ && components_->retry.has_value())
421 {
422 return components_->retry;
423 }
424 return std::nullopt;
425 }

References components_.

◆ get_timeout()

auto kcenon::thread::job::get_timeout ( ) const -> std::optional<std::chrono::milliseconds>
nodiscard

Gets the timeout duration for this job.

Returns
The job's timeout, or std::nullopt if not set

Implementation details:

  • Returns the timeout if set via with_timeout()
  • Returns std::nullopt if no timeout was configured
Returns
The job's timeout or std::nullopt

Definition at line 436 of file job.cpp.

437 {
438 if (components_ && components_->timeout.has_value())
439 {
440 return components_->timeout;
441 }
442 return std::nullopt;
443 }

References components_.

◆ has_components()

auto kcenon::thread::job::has_components ( ) const -> bool
nodiscard

Checks if this job has any composed components.

Returns
true if any with_*() method has been called, false otherwise

Implementation details:

  • Simple null check on the components pointer
  • Useful for conditional logic based on composition state
Returns
true if any with_*() method has been called

Definition at line 468 of file job.cpp.

469 {
470 return components_ != nullptr;
471 }

References components_.

◆ has_explicit_cancellation()

auto kcenon::thread::job::has_explicit_cancellation ( ) const -> bool
nodiscard

Checks if this job has an explicit cancellation set via composition.

Returns
true if with_cancellation() was called

Implementation details:

Returns
true if with_cancellation() was called

Definition at line 454 of file job.cpp.

455 {
456 return components_ && components_->has_explicit_cancellation;
457 }

References components_.

◆ invoke_callbacks()

auto kcenon::thread::job::invoke_callbacks ( const common::VoidResult & result) -> void
protected

Invokes the completion callbacks if they are set.

This method should be called by derived classes or the job execution framework after do_work() completes. It handles invoking both the on_complete and on_error callbacks as appropriate.

Parameters
resultThe result from do_work()

Implementation details:

  • Invokes on_complete callback with the full result
  • Invokes on_error callback only if result is an error
  • Order: on_error is called first (if applicable), then on_complete
  • Exceptions from callbacks are not caught (propagate to caller)
Parameters
resultThe result from do_work()
Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/job_builder.h.

Definition at line 484 of file job.cpp.

485 {
486 if (!components_)
487 {
488 return;
489 }
490
491 // Invoke error callback first if result is an error
492 if (result.is_err() && components_->on_error)
493 {
494 components_->on_error(result.error());
495 }
496
497 // Always invoke on_complete callback if set
498 if (components_->on_complete)
499 {
500 components_->on_complete(result);
501 }
502 }

Referenced by kcenon::thread::job_builder::built_job::do_work().

Here is the caller graph for this function:

◆ set_cancellation_token()

auto kcenon::thread::job::set_cancellation_token ( const cancellation_token & token) -> void
virtual

Sets a cancellation token that can be used to cancel the job.

Sets the cancellation token for cooperative cancellation.

Parameters
tokenThe cancellation token to associate with this job.

Implementation details:

  • Stores cancellation token for use during job execution
  • Enables cooperative cancellation (job checks token periodically)
  • Thread-safe assignment (cancellation_token is thread-safe)
  • Token can be checked during long-running operations

Cancellation Model:

  • Cooperative: job must check token voluntarily
  • Non-preemptive: job won't be forcibly stopped
  • Graceful: allows cleanup before termination

Usage Pattern:

  1. Create cancellation_token
  2. Set token on jobs before submission
  3. Job checks token during execution
  4. External code can signal cancellation
Parameters
tokenCancellation token for cooperative cancellation

Definition at line 163 of file job.cpp.

163 {
164 cancellation_token_ = token;
165 }

◆ set_job_queue()

auto kcenon::thread::job::set_job_queue ( const std::shared_ptr< job_queue > & job_queue) -> void
virtual

Associates this job with a specific job_queue.

Associates this job with a job queue for scheduling.

Once assigned, the job can be aware of the queue that manages it, enabling scenarios like re-enqueuing itself upon partial failure, or querying the queue for state (depending on the queue's interface).

Parameters
job_queueA shared pointer to the job_queue instance.

Implementation Detail

  • Stored internally as a std::weak_ptr. If the queue is destroyed, the pointer becomes invalid.

Implementation details:

  • Stores weak reference to prevent circular dependencies
  • Allows job to interact with its queue if needed
  • Automatic cleanup when queue is destroyed
  • Used for advanced job management scenarios

Weak Reference Benefits:

  • Prevents memory leaks from circular references
  • Queue can be destroyed without affecting jobs
  • Jobs can check if queue is still alive
  • No impact on queue lifetime management

Use Cases:

  • Jobs that need to submit additional jobs
  • Self-scheduling or recursive jobs
  • Jobs that need queue statistics
  • Advanced workflow management
Parameters
job_queueShared pointer to the job queue

Definition at line 219 of file job.cpp.

220 {
221 job_queue_ = job_queue;
222 }

◆ to_string()

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

Provides a string representation of the job for logging or debugging.

Provides a string representation of this job.

By default, this returns the job's name. Derived classes can override to include extra diagnostic details (e.g., job status, data contents, etc.).

Returns
A string describing the job (e.g., name_).

Example

std::shared_ptr<my_job> job_ptr = std::make_shared<my_job>();
// ...
std::string desc = job_ptr->to_string(); // "my_custom_job", for instance

Implementation details:

  • Formats job name for display purposes
  • Used in debugging, logging, and diagnostics
  • Consistent format across all job types
  • Thread-safe operation (accesses immutable name)

Output Format:

  • "job: <name>" where <name> is the job's descriptive name
  • Simple, readable format for human consumption
  • Suitable for log files and debug output
Returns
Formatted string representation of the job

Reimplemented in kcenon::thread::dag_job.

Definition at line 262 of file job.cpp.

262{ return formatter::format("job: {}", name_); }
static auto format(const char *formats, const FormatArgs &... args) -> std::string
Formats a narrow-character string with the given arguments.
Definition formatter.h:132

References kcenon::thread::utils::formatter::format().

Here is the call graph for this function:

◆ with_cancellation()

auto kcenon::thread::job::with_cancellation ( const cancellation_token & token) -> job&

Attaches a cancellation token to this job via composition.

The cancellation token enables cooperative cancellation of the job. The job should periodically check the token and abort if cancelled.

Parameters
tokenThe cancellation token to use
Returns
Reference to this job for method chaining

Thread Safety

  • The token itself is thread-safe for cancellation requests
  • The job must cooperatively check the token during execution

Example

auto job = std::make_unique<my_job>()
// Later, from another thread
token.cancel();
Provides a mechanism for cooperative cancellation of operations.
void cancel()
Cancels the operation.
auto with_cancellation(const cancellation_token &token) -> job &
Attaches a cancellation token to this job via composition.
Definition job.cpp:350

Implementation details:

  • Sets the cancellation token on the job
  • Marks the job as having explicit cancellation for querying
  • Enables fluent method chaining
Parameters
tokenThe cancellation token to use
Returns
Reference to this job for chaining

Definition at line 350 of file job.cpp.

351 {
352 cancellation_token_ = token;
353 ensure_components().has_explicit_cancellation = true;
354 return *this;
355 }
auto ensure_components() -> job_components &
Ensures components_ is allocated (lazy initialization).
Definition job.cpp:279

◆ with_on_complete()

auto kcenon::thread::job::with_on_complete ( std::function< void(common::VoidResult)> callback) -> job&

Attaches a completion callback to this job.

The callback will be invoked after do_work() completes, regardless of success or failure. The callback receives the VoidResult from do_work().

Parameters
callbackFunction to call with the job's result
Returns
Reference to this job for method chaining

Thread Safety

  • The callback is invoked on the same thread that executes do_work()
  • Ensure callback is thread-safe if it accesses shared resources

Example

auto job = std::make_unique<my_job>()
->with_on_complete([](auto result) {
if (result.is_ok()) {
std::cout << "Job completed successfully\n";
} else {
std::cout << "Job failed: " << result.error().message << "\n";
}
});
auto with_on_complete(std::function< void(common::VoidResult)> callback) -> job &
Attaches a completion callback to this job.
Definition job.cpp:299
A template class representing either a value or an error.
bool is_ok() const noexcept
Checks if the result is successful.

Implementation details:

  • Uses lazy initialization to avoid memory overhead for simple jobs
  • Returns *this to enable fluent method chaining
  • Callback is stored and invoked by invoke_callbacks()
Parameters
callbackFunction to call with the job's result
Returns
Reference to this job for chaining

Definition at line 299 of file job.cpp.

300 {
301 ensure_components().on_complete = std::move(callback);
302 return *this;
303 }
@ callback
Call user callback for custom decision.

References kcenon::thread::callback.

◆ with_on_error()

auto kcenon::thread::job::with_on_error ( std::function< void(const common::error_info &)> callback) -> job&

Attaches an error callback to this job.

The callback will be invoked only if do_work() returns an error. This is more specific than with_on_complete() for error-only handling.

Parameters
callbackFunction to call with the error information
Returns
Reference to this job for method chaining

Example

auto job = std::make_unique<my_job>()
->with_on_error([](const auto& err) {
log_error("Job failed: code={}, message={}", err.code, err.message);
});
auto with_on_error(std::function< void(const common::error_info &)> callback) -> job &
Attaches an error callback to this job.
Definition job.cpp:316

Implementation details:

Parameters
callbackFunction to call with the error information
Returns
Reference to this job for chaining

Definition at line 316 of file job.cpp.

317 {
318 ensure_components().on_error = std::move(callback);
319 return *this;
320 }

References kcenon::thread::callback.

◆ with_priority()

auto kcenon::thread::job::with_priority ( job_priority priority) -> job&

Sets the priority level for this job.

Priority can be used by job queues and schedulers to determine execution order. Higher priority jobs are typically executed first.

Parameters
priorityThe priority level to set
Returns
Reference to this job for method chaining

Example

auto job = std::make_unique<my_job>()
->with_on_complete([](auto) { std::cout << "Done\n"; });
auto with_priority(job_priority priority) -> job &
Sets the priority level for this job.
Definition job.cpp:333
@ high
High priority, time-sensitive tasks.

Implementation details:

  • Priority is stored in optional to distinguish "not set" from "normal"
  • Can be queried by schedulers via get_priority()
  • Does not affect execution order in basic job_queue (for typed pools)
Parameters
priorityThe priority level to set
Returns
Reference to this job for chaining

Definition at line 333 of file job.cpp.

334 {
335 ensure_components().priority = priority;
336 return *this;
337 }
@ priority
Priority-based scheduling.

References kcenon::thread::priority.

◆ with_retry()

auto kcenon::thread::job::with_retry ( const retry_policy & policy) -> job&

Attaches a retry policy to this job.

When the job fails, it can be automatically retried according to the specified retry policy. The executor must support retry behavior.

Parameters
policyThe retry policy to use
Returns
Reference to this job for method chaining

Supported Policies

Example

auto job = std::make_unique<my_job>()
->with_on_error([](auto& err) { log("Retry exhausted: {}", err.message); });
auto with_retry(const retry_policy &policy) -> job &
Attaches a retry policy to this job.
Definition job.cpp:368
static auto exponential_backoff(std::size_t max_attempts, std::chrono::milliseconds initial_delay=std::chrono::milliseconds(100), double multiplier=2.0, std::chrono::milliseconds max_delay=std::chrono::milliseconds(30000), bool use_jitter=false) -> retry_policy
Creates an exponential backoff retry policy.

Implementation details:

  • Stores the retry policy in components for executor access
  • The executor is responsible for implementing retry logic
  • Enables fluent method chaining
Parameters
policyThe retry policy to use
Returns
Reference to this job for chaining

Definition at line 368 of file job.cpp.

369 {
370 ensure_components().retry = policy;
371 return *this;
372 }

◆ with_timeout()

auto kcenon::thread::job::with_timeout ( std::chrono::milliseconds timeout) -> job&

Sets a timeout for job execution.

If the job does not complete within the specified duration, it may be cancelled (requires executor support for timeout handling).

Parameters
timeoutMaximum execution time allowed
Returns
Reference to this job for method chaining

Note

  • Timeout enforcement requires executor/queue support
  • The job should check cancellation token for cooperative timeout

Example

auto job = std::make_unique<my_job>()
->with_timeout(std::chrono::seconds(30))
->with_on_error([](auto& err) { log("Timed out: {}", err.message); });
auto with_timeout(std::chrono::milliseconds timeout) -> job &
Sets a timeout for job execution.
Definition job.cpp:385

Implementation details:

  • Stores timeout duration in components for executor access
  • The executor is responsible for implementing timeout logic
  • Enables fluent method chaining
Parameters
timeoutMaximum execution time allowed
Returns
Reference to this job for chaining

Definition at line 385 of file job.cpp.

386 {
387 ensure_components().timeout = timeout;
388 return *this;
389 }

Member Data Documentation

◆ cancellation_token_

cancellation_token kcenon::thread::job::cancellation_token_
protected

The cancellation token associated with this job.

This token can be used to cancel the job during execution. The job should periodically check this token and abort if it is cancelled.

Examples
/home/runner/work/thread_system/thread_system/include/kcenon/thread/core/job_builder.h, and job_cancellation_example.cpp.

Definition at line 504 of file job.h.

Referenced by cancellable_long_job::do_work(), kcenon::thread::future_job< R >::do_work(), kcenon::thread::job_builder::built_job::do_work(), and get_cancellation_token().

◆ components_

std::unique_ptr<job_components> kcenon::thread::job::components_
private

Composed components for this job.

Lazily allocated when first with_*() method is called. This enables the composition pattern without memory overhead for jobs that don't use composition.

Definition at line 535 of file job.h.

Referenced by get_priority(), get_retry_policy(), get_timeout(), has_components(), and has_explicit_cancellation().

◆ data_

std::vector<uint8_t> kcenon::thread::job::data_
protected

An optional container of raw byte data that may be used by the job.

If the constructor without the data parameter is used, this vector will remain empty unless manually populated by derived classes or other means.

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

Definition at line 488 of file job.h.

Referenced by kcenon::thread::job_builder::built_job::do_work().

◆ enqueue_time_

std::chrono::steady_clock::time_point kcenon::thread::job::enqueue_time_
private

Time when the job was created.

Captured during construction, used for wait time calculations in diagnostics.

Definition at line 526 of file job.h.

Referenced by get_enqueue_time().

◆ job_id_

std::uint64_t kcenon::thread::job::job_id_
private

Unique identifier for this job.

Generated automatically during construction, unique within the lifetime of the application.

Definition at line 518 of file job.h.

Referenced by get_job_id().

◆ job_queue_

std::weak_ptr<job_queue> kcenon::thread::job::job_queue_
protected

A weak reference to the job_queue that currently manages this job.

This reference can expire if the queue is destroyed, so always lock it into a std::shared_ptr before use to avoid invalid access.

Definition at line 496 of file job.h.

◆ name_

std::string kcenon::thread::job::name_
protected

The descriptive name of the job, used primarily for identification and logging.

Definition at line 480 of file job.h.

◆ next_job_id_

std::atomic< std::uint64_t > kcenon::thread::job::next_job_id_ {0}
staticprivate

Static counter for generating unique job IDs.

Definition at line 510 of file job.h.


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