Overview / System & concurrency

concurrency

Job system with groups and execution modes: persistent worker threads or detached asynchronous routines.

Always compiled: part of the core build.Include #include <ethereal/cpp/concurrency/concurrency_inc.hpp>C layer

concurrency_inc.hpp

#include <ethereal/cpp/concurrency/concurrency_inc.hpp>

jobs.hpp

#include <ethereal/cpp/concurrency/jobs.hpp>
alias

void

Ethereal::Job#
using ETL_JobFunc = std::function< void( std::stop_token ) >;
enum

EOperationMode

Ethereal::Job#
C++
enum class EOperationMode : ETL_UINT8
{
    /// @brief  Persistent routines with scheduling.
    ///         The routine is submitted for processing through the internal task queue.
    ///         Processing is performed by the worker threads created during manager initialization, @ref Initialize.
    ///
    ///         In this mode, routines are queued for processing and filtered by group and priority.
    ///         If no worker thread is available to execute the task, an error will be generated and the task execution will be ignored.
    ///
    ///         Routines intended for continuous execution (infinite loop) must be flagged via @input bAllowInfiniteLoop.
    ///         Keep in mind that a continuously running routine (infinite loop) will consume the entire processing capacity of the target worker thread.
    ///         Consider using the @ref eAsyncDetached operation mode in such cases.
    ///
    /// @details  When adding a task, if a worker thread already contains tasks from the same group, it will execute on that same worker thread.
    ///           Otherwise, the task is assigned to the worker thread with the highest processing availability.
    ///
    /// @warning  Pay attention to the number of worker threads created; it must not exceed the CPU limit.
    ///           If the number of asynchronous routines created (not yet finished) plus worker threads exceeds the CPU limit, a warning will be generated.
    ///
    ePersistentWorkers = 0,

    /// @brief  Asynchronous routines without scheduling or filtering.
    ///         The routine is executed immediately upon creation using a helper routine created with std::jthread.
    ///         Does not depend on worker thread initialization, however it still depends on manager initialization, @ref Initialize.
    ///         Ideal for single, independent, or short-lived tasks.
    ///
    ///         In this mode, routine priority levels and group filtering are ignored.
    ///         Routines intended for continuous execution (infinite loop) must be flagged via @input bAllowInfiniteLoop.
    ///
    ///         Task priority levels will not be applied when the manager is operating in this state.
    ///
    /// @warning  Pay attention to the number of async routines created; it must not exceed the CPU limit.
    ///           If the number of asynchronous routines created (not yet finished) plus worker threads exceeds the CPU limit, a warning will be generated.
    ///
    eAsyncDetached
};

Identification of created routine operation modes.

enum

EJobGroup

Ethereal::Job#
C++
enum class EJobGroup : ETL_UINT8
{
    /// @brief    Generic group. Default.
    eGeneric = 0,

    /// @brief    Instance group.
    eInstance,

    /// @brief    Manager group.
    eManager,

    /// @brief    Tick/update group.
    eTick,

    /// @brief    Network group.
    eNetwork,

    /// @brief    API task group.
    eApi,

    /// @brief    Object group.
    eObject,

    /// @brief    Additional groups, without specific definition.
    eMisc_01,
    eMisc_02,
    eMisc_03,
    eMisc_04,
    eMisc_05,

    /// @brief    Array-only (for internal checks only, never use)
    eLast
};

Identification of task groups.

function

JobGroupToString

Ethereal::Job#
const char * JobGroupToString( const EJobGroup Group ) noexcept;

Retrieves the task group as a C-string.

Task group in C-string format.
class

CJobManager

Ethereal::Job#

Asynchronous task manager class.

class CJobManager final

There is no guarantee that it is completely thread-safe. Some functions are protected by mutexes from both the @CJobManager class and internal mutexes. Synchronization is the responsibility of the caller. It must not be directly inherited by any structure, class, or object.

function

Instance

#
static CJobManager & Instance() noexcept;

Retrieves the singleton instance of the job manager.

Reference to the unique @CJobManager instance.
function

Initialize

#
bool Initialize( const std::size_t WorkerCount = std::thread::hardware_concurrency(), const bool bAllowErrorReport = false );

Initializes the job manager with the specified number of worker threads.

If using only asynchronous tasks EOperationMode::eAsyncDetached, consider initializing with WorkerCount = 0.

Safe to call from several threads at once: only one succeeds. If a worker thread cannot be created it throws (std::system_error), and the manager is left stopped and unlocked, ready for a new call (since 2026-10-16).

WorkerCount
Number of worker threads to be created (by default, equal to the number of CPU cores).
bAllowErrorReport
Enables generation of internal error reports.
@true if the system was successfully initialized. @false if initialization fails, or when the library is not licensed.
Must be called before creating any tasks.
Pay attention to the number of worker threads or asynchronous routines created; it must not exceed the CPU limit. If the number of asynchronous routines created (not yet finished) plus worker threads exceeds the CPU limit, a warning will be generated.
function

Stop

#
void Stop( void );

Stops all pending tasks and terminates active worker threads.

This function must be called before shutting down the application or reinitializing the job manager. Ensures proper resource release and safe system shutdown.
function

DumpBadJobs

#
ETL_INT32 DumpBadJobs( const std::size_t iBadJobsBufferLength, char * sBadJobsBufferOut );

Generates a textual report of failed jobs into a C buffer.

Iterates through the internal list of jobs that were not properly terminated and writes a formatted report directly into a buffer provided by the caller. This version is intended for integration with C APIs, legacy systems, or low-level layers.

iBadJobsBufferLength
Total size of the output buffer, in bytes.
sBadJobsBufferOut
Pointer to the buffer that will receive the report.
Result code: - 0 : Success - 1 : Manager not initialized or error reporting disabled - 2 : Invalid buffer pointer - 3 : Insufficient buffer size to hold the full report
This function is thread-safe . Access to internal data is protected by a mutex.
function

DumpBadJobs

#
ETL_INT32 DumpBadJobs( std::string & sBadJobsOut );

Generates a textual report of jobs with errors or not properly terminated. Iterates through the internal list of problematic jobs registered by the job manager and builds a formatted output containing relevant debugging information.

The content is written directly into the provided output @std::string.

sBadJobsOut
Output string that will receive the error report.
Result code: - 0 : Success - 1 : Manager not initialized or error reporting disabled
This function is thread-safe . Access to internal data is protected by a mutex.
function

DumpBadJobs

#
ETL_INT32 DumpBadJobs( String::CAString & sBadJobsOut );

Generates a textual report of failed jobs using @CAString.

Iterates through the internal list of jobs that were not properly terminated and builds a formatted report containing relevant debugging and diagnostic information. This version uses the internal @String::CAString class, avoiding direct dependency on @std::string.

sBadJobsOut
Output string that will receive the error report.
Result code: - 0 : Success - 1 : Manager not initialized or error reporting disabled
This function is thread-safe . Access to internal data is protected by a mutex.
function

DumpStats

#
ETL_INT32 DumpStats( const std::size_t iBadJobsBufferLength, char * sBadJobsBufferOut );

Generates a textual report with job manager statistics into a C buffer. Produces a formatted report containing internal job manager statistics and writes the result directly into a buffer provided by the caller. This version is intended for integration with C APIs or low-level layers.

iBadJobsBufferLength
Total size of the output buffer, in bytes.
sBadJobsBufferOut
Pointer to the buffer that will receive the report.
Result code: - 0 : Success - 1 : Manager not initialized - 2 : Invalid buffer pointer - 3 : Insufficient buffer size to hold the full report
This function is thread-safe . Access to internal data is protected by a mutex.
function

DumpStats

#
ETL_INT32 DumpStats( std::string & sStatsOut );

Generates a textual report with job manager statistics. Produces a formatted report containing internal manager information, such as thread counters, executed jobs, and recorded failures. The content is written directly into the provided output string.

sStatsOut
Output @std::string that will receive the statistics report.
Result code: - 0 : Success - 1 : Manager not initialized
This function is thread-safe . Access to internal data is protected by a mutex.
function

DumpStats

#
ETL_INT32 DumpStats( String::CAString & sStatsOut );

Generates a textual report with job manager statistics using CAString. Builds a formatted report containing internal job manager statistics, writing the result into an instance of String::CAString. The content is written directly into the provided output string.

sStatsOut
Output @CAString that will receive the statistics report.
Result code: - 0 : Success - 1 : Manager not initialized
This function is thread-safe . Access to internal data is protected by a mutex.
function

CreateJob

#
void CreateJob( const char * JobName, const EJobGroup GroupID, ETL_JobFunc FuncCB, const EOperationMode OperationMode, const bool bAllowInfiniteLoop = false, const ETL_DOUBLE dMaxExecutionTimeExp = 0.0, const bool bProfileExecution = false );

Creates and submits a new asynchronous job to the job management system. It is recommended to use the @macros ETL_JOB_SUBMIT, ETL_JOBLOOP_SUBMIT, and ETL_JOB_SUBMIT_SAFE instead of calling this function directly.

JobName
Identifier name of the job (for debugging or future tracking).
GroupID
ID of the group to which the job belongs (used for balancing and affinity). See EJobGroup.
FuncCB
Callback function to be executed by the job.
bAllowInfiniteLoop
Defines whether the job may run indefinitely without generating alerts or triggering internal checks.
dMaxExecutionTimeExp
Maximum expected execution time (in seconds). Used to detect anomalies during job execution.
bProfileExecution
Indicates whether profiling should be performed during job execution.
Jobs are dispatched according to availability and the defined prioritization policy.
Jobs with infinite loops cannot currently be accounted for by the Profiler.

parallel_for.hpp

#include <ethereal/cpp/concurrency/parallel_for.hpp>

A thread seam for "run these N tasks and wait", and its default adapter over the job system (Job::CJobManager).

IParallelFor is the shape the modules use when they have work to spread over threads but must not create threads themselves: the integrator runs the tasks and Run returns once all of them are done. CJobParallelFor runs them on the workers of Job::CJobManager, and the calling thread works too.

The adapter is the one of Ai::Tokenizer (CJobParallelFor in ai/tokenizer/batch.hpp), moved here so that every module can take it without depending on the Tokenizer (AI-04, T6). The Tokenizer keeps its own for now.

struct

IParallelFor

Ethereal::Job#
C++
struct   ETL_API   IParallelFor
{
    /// @brief  Number of threads one Run may use (at least one).
    virtual ETL_UINT32 Workers( void ) const ETL_NOEXCEPT = 0;

    ///
    /// Run
    ///
    /// @brief  Runs @p pFn for every task index from 0 to @p uTasks - 1 and waits.
    ///
    /// @param uTasks    Number of tasks.
    /// @param pFn        Task function, called with @p pCtx and the task index.
    /// @param pCtx        Context passed to every call.
    ///
    virtual void Run( ETL_UINT32 uTasks, void ( *pFn )( void * pCtx, ETL_UINT32 uTask ) ETL_NOEXCEPT, void * pCtx ) ETL_NOEXCEPT = 0;

    /// @brief  Destructor.
    virtual ~IParallelFor() = default;
};

Runs a number of tasks on threads the integrator owns, and returns only when every task is done.

A task function may run on several threads at the same time, with different task indices. The module that calls Run never creates threads.

class

CInlineParallelFor

Ethereal::Job#

Runs every task on the calling thread, in order. The default of the modules when no IParallelFor is given.

class CInlineParallelFor final : public IParallelFor
function

Workers

#
ETL_UINT32 Workers( void ) const noexcept override
function

Run

#
void Run( const ETL_UINT32 uTasks, void ( *pFn )( void * pCtx, ETL_UINT32 uTask ) noexcept, void * pCtx ) noexcept override
class

CJobParallelFor

Ethereal::Job#

IParallelFor over the workers of Job::CJobManager.

class CJobParallelFor final : public IParallelFor

Workers counts the calling thread: Run submits up to Workers - 1 jobs (at most the twelve groups of Job::EJobGroup), each in a group of its own so the manager spreads them over different workers, and every job and the calling thread take tasks from an atomic counter. The calling thread then waits until every task is done.

The state of a Run lives in one small block of the allocator, freed by the last one to leave it, and each job is one std::function holding one pointer: a Run allocates (a task does not). A job that starts late finds no task and leaves, so Run never waits for a job that cannot start. When the block or a job cannot be created, the calling thread does the tasks. The manager must be initialized with at least Workers - 1 workers, and the allocator must outlive every job submitted.

Thread safety: Run may be called from several threads at once.

const

kMaxWorkers

#
static constexpr ETL_UINT32 kMaxWorkers = 13u;

Most threads one Run uses: the twelve groups of Job::EJobGroup, plus the calling thread.

constructor

CJobParallelFor

#
explicit CJobParallelFor( ETL_UINT32 uWorkers, const char * pJobName = nullptr, Memory::IAllocator * pAlloc = nullptr ) noexcept;
uWorkers
Threads to use, the calling thread included. Zero becomes one, above kMaxWorkers becomes kMaxWorkers.
pJobName
Name of the jobs in the manager's reports. Must live as long as the adapter. Null is "parallel_for".
pAlloc
Allocator of the state of each Run. Null is the default.
function

Workers

#
ETL_UINT32 Workers( void ) const noexcept override
function

Run

#
void Run( ETL_UINT32 uTasks, void ( *pFn )( void * pCtx, ETL_UINT32 uTask ) noexcept, void * pCtx ) noexcept override;