What it does
- <code>CJobManager</code> with 12 job groups
- Default worker count equal to the number of logical cores
- Report of problematic jobs and statistics
This module has no guide yet: start with the summary above and the reference in the tabs.
Job system with groups and execution modes: persistent worker threads or detached asynchronous routines.
using ETL_JobFunc = std::function< void( std::stop_token ) >;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 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.
const char * JobGroupToString( const EJobGroup Group ) noexcept;Retrieves the task group as a C-string.
Asynchronous task manager class.
class CJobManager finalThere 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.
static CJobManager & Instance() noexcept;Retrieves the singleton instance of the job manager.
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).
WorkerCountbAllowErrorReportvoid Stop( void );Stops all pending tasks and terminates active worker threads.
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.
iBadJobsBufferLengthsBadJobsBufferOutETL_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.
sBadJobsOutETL_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.
sBadJobsOutETL_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.
iBadJobsBufferLengthsBadJobsBufferOutETL_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.
sStatsOutETL_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.
sStatsOutvoid 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.
JobNameGroupIDEJobGroup.FuncCBbAllowInfiniteLoopdMaxExecutionTimeExpbProfileExecutionA 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 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.
Runs every task on the calling thread, in order. The default of the modules when no IParallelFor is given.
class CInlineParallelFor final : public IParallelForIParallelFor over the workers of Job::CJobManager.
class CJobParallelFor final : public IParallelForWorkers 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.
static constexpr ETL_UINT32 kMaxWorkers = 13u;Most threads one Run uses: the twelve groups of Job::EJobGroup, plus the calling thread.
explicit CJobParallelFor( ETL_UINT32 uWorkers, const char * pJobName = nullptr, Memory::IAllocator * pAlloc = nullptr ) noexcept;uWorkerspJobNamepAllocETL_UINT32 Workers( void ) const noexcept overridevoid Run( ETL_UINT32 uTasks, void ( *pFn )( void * pCtx, ETL_UINT32 uTask ) noexcept, void * pCtx ) noexcept override;C layer of the Concurrency module: the job system.
Under this layer sits the process wide 'CJobManager' singleton of 'ethereal/cpp/concurrency/jobs.hpp'. There is one job system per process, so the functions take no handle: the C layer owns the life cycle with ETLC_JobsStart and ETLC_JobsStop. When C++ code already started the manager, ETLC_JobsStart returns ETLC_ERR_ALREADY_INITIALIZED and the C side does not submit to it.
A job is a C function 'void ( )( void )' and its argument. The C++ manager has no way to wait for a job. This layer adds it: each job carries a ticket that records whether the job ran or was dropped (no worker, or still queued when ETLC_JobsStop ran). ETLC_JobsWait waits for one ticket, ETLC_JobsWaitAll for every job submitted through this layer.
Two modes, the ones of the C++ side. In ETLC_JOBS_MODE_WORKER the job goes to the queue of a worker thread. In ETLC_JOBS_MODE_ASYNC it runs at once on a detached thread of its own, also with zero workers. ETLC_JobsStop does not wait for async jobs: call ETLC_JobsWaitAll first.
Never call ETLC_JobsStart, ETLC_JobsStop, ETLC_JobsWaitAll, or ETLC_JobsWait on its own ticket from inside a job: the job would wait for itself.
Left out: job names, groups, infinite loop jobs and the execution time check. Every C job runs in the generic group.
Every export returns 'int'. Zero is success, negative is an error. The values are part of the ABI.
#define ETLC_JOBS_OK ETLC_OKSuccess.
#define ETLC_JOBS_ERR_DROPPED ( -1501 )The job was dropped before running: worker mode without workers.
#define ETLC_JOBS_ERR_NO_REPORT ( -1502 )Error reporting was not enabled at start.
#define ETLC_JOBS_WORKERS_AUTO ( ( size_t ) -1 )Number of workers for ETLC_JobsStart: one per hardware thread.
#define ETLC_JOBS_MODE_WORKER 0The job goes to the queue of a worker thread.
#define ETLC_JOBS_MODE_ASYNC 1The job runs at once on a detached thread of its own.
#define ETLC_JOBS_STATE_PENDING 0The job has not finished yet.
#define ETLC_JOBS_STATE_DONE 1The job ran and returned.
#define ETLC_JOBS_STATE_DROPPED 2The job never ran.
typedef void ( * ETLC_JobsFn )( void * pArg );A job. Runs once, on a thread of the job system.
typedef struct ETLC_JobsTicket_t * ETLC_JobsTicket;Opaque ticket of a submitted job, allocated by the library. Release it.
const char * ETLC_JobsStatusName( int iStatus ) noexcept;Name of a status code, in English. Never null: an unknown code gives "unknown".
int ETLC_JobsStart( size_t uWorkers, int bErrorReport ) noexcept;Starts the job system with its worker threads.
uWorkersbErrorReportint ETLC_JobsStop( void ) noexcept;Stops the worker threads. Waits for the jobs they are running, and drops the ones still queued. Async jobs go on.
int ETLC_JobsIsStarted( int * pStarted ) noexcept;Writes 1 in *pStarted when the job system was started by this layer, 0 otherwise.
int ETLC_JobsWorkerCount( size_t * pCount ) noexcept;Writes the number of worker threads in *pCount. Zero when stopped.
int ETLC_JobsSubmit( ETLC_JobsFn pFn, void * pArg, int iMode, ETLC_JobsTicket * phTicket ) noexcept;Submits a job.
pFnpArgiModephTicketint ETLC_JobsWait( ETLC_JobsTicket hTicket, int * pState ) noexcept;Waits until the job ran or was dropped, and writes ETLC_JOBS_STATE_DONE or ETLC_JOBS_STATE_DROPPED in *pState.
int ETLC_JobsPoll( ETLC_JobsTicket hTicket, int * pState ) noexcept;Writes the state of the job, one of the ETLC_JOBS_STATE_* values, in *pState. Does not wait.
int ETLC_JobsRelease( ETLC_JobsTicket hTicket ) noexcept;Releases a ticket. The job is not affected. Accepts null.
int ETLC_JobsWaitAll( void ) noexcept;Waits until every job submitted through this layer ran or was dropped.
int ETLC_JobsDumpStats( char * pOut, size_t uCap, size_t * pWritten ) noexcept;Writes the statistics report of the job manager, and a '\0'.
pOutuCappWrittenint ETLC_JobsDumpBadJobs( char * pOut, size_t uCap, size_t * pWritten ) noexcept;Writes the report of the jobs that failed, and a '\0'. Same buffer rules as ETLC_JobsDumpStats. ETLC_JOBS_ERR_NO_REPORT when the job system was started without error reporting.
This module has no guide yet: start with the summary above and the reference in the tabs.