Repository navigation
en architecture jobs threading
中文 | English | Docs | Repository
Nullus retains two logical layers sharing one compute scheduler: JobSystem executes jobs and owns the worker pool; TaskGraph manages dependencies and named execution queues. Blocking background I/O has a separately budgeted pool. The unification audit, contracts, and examples are recorded in Docs/TaskSystemUnification.md.
Runtime/Base/Jobs provides the native scheduling interface.
NLS::Base::Jobs::JobSystemConfig config;
config.workerCount = 4; // kAutoJobWorkerCount derives a default from the hardware
config.backgroundWorkerCount = 1;
NLS::Base::Jobs::InitializeJobSystem(config);TryInitializeJobSystem is the ownership-aware variant: it returns true when the caller acquires explicit ownership, including when a graph lease already started the runtime. Code using it must call ShutdownJobSystem only on the true branch. The first initializer fixes the worker configuration; later graphs reuse it. The last application owner and graph lease jointly determine shutdown.
JobHandle{} is always complete.
| Interface | Purpose |
|---|---|
ScheduleJob |
Short CPU work |
ScheduleDifferentJobsConcurrent |
A batch of distinct concurrent jobs |
ScheduleJobForEach |
Batched iteration with a caller-controlled batchSize
|
Native IJob / IJobParallelFor adapters |
Typed wrappers for C++ users |
JobBatchDispatcher |
Batched dispatch and multi-dependency fan-in |
-
Completewaits and clears the handle. -
CompleteNoClearkeeps the caller's copy valid for later queries. -
HasBeenSyncedreports whether the handle reached a terminal state. -
GetCompletionStatusdistinguishes success, failure, cancellation and pending work.RequestCancelcancels unstarted compute groups; a started group observes a cooperative request throughIsCancellationRequested. Background I/O retains shutdown cancellation only. - Foreground jobs may supply a cancel callback to release their payload. It runs at most once for queued or dependency-waiting work cancelled by immediate shutdown or by a failed or cancelled dependency, and never once the job has started executing.
JobBatchDispatcher supports explicit per-dispatcher kicks, destructor kicks, configured auto-kick thresholds, and multi-dependency fan-in handles. A dispatcher is a caller-owned batching helper and is not thread-safe; producers adding to or kicking it from multiple threads must serialize access.
IsCompleted and Complete both make pending batches worker-visible before querying or waiting. There is no global ScheduleBatchedJobs; batch visibility is per dispatcher, per fan-in creation, or per handle.
-
workerCount = 0is an explicit synchronous and test mode. - Completion may execute eligible jobs on the calling thread to advance dependencies.
- Waiting only helps jobs on the waited fence's dependency chain, or jobs marked
GuaranteedNoSyncWait. - A
GuaranteedNoSyncWaitcallback runs inside a no-sync-wait scope, where callingCompleterecords a violation and returns without blocking.
-
ScheduleJobForEachrejects iteration counts or batch sizes beyond the nativeintrange planner. - Compute workers use per-worker priority queues and work stealing. Group state still uses a mutex-protected registry.
maxPendingJobCountbounds accepted foreground callbacks and, separately, background jobs plus main continuations; saturation rejects without taking caller payload ownership. - Cross-queue dependency promotion uses explicit notifications plus a bounded timed fallback. Correctness does not depend on the fallback, but heavy cross-queue traffic can still pay the polling latency.
Job callbacks receive raw void* payloads whose lifetime the caller owns; the payload must stay alive until the handle reaches a terminal state or its cleanup callback has run. Callbacks can run during completion or shutdown, so they must not assume a particular thread.
Nullus provides no managed-container race checking such as NativeArray or safety handles. Shared mutable state must be protected by the caller with atomics, locks, immutable snapshots, or dependency ordering. JobSafetyPolicy describes synchronous-wait safety only; it does not prove memory safety.
Callbacks should not throw. If a foreground, background, combine, cancel, or cleanup callback throws, the scheduler catches it at the boundary, records JobViolationKind::CallbackException, and advances the handle along the documented failure or cancellation path.
- Long-running or IO-heavy work uses
ScheduleBackgroundJob. - Main-thread follow-up work uses
ScheduleMainThreadContinuationand only executes fromDrainMainThreadContinuationson the registered owner thread. - Ready continuations are promoted into a dedicated ready queue so each drain consumes ready work instead of scanning every blocked continuation.
- The editor update loop drains a bounded budget once per frame after delayed editor actions.
- Shutdown does not implicitly execute main-thread continuations; owners must drain what they need before stopping the JobSystem.
The editor's background task path goes through the shared background queue instead of private threads, enforces a task capacity limit, rejects submissions after stop, and completes submitted handles in its destructor.
JobSystemConfig::enableDiagnostics collects bounded snapshots, and DisallowJobSyncWaitScope records structured violations when a blocking wait is attempted inside a no-wait scope.
JobBindings.h exposes a minimal C-compatible subset: structSize, NLS_JOB_BINDING_VERSION, opaque handle IDs, named priority and safety constants, and explicit status codes.
- When the runtime is stopped, non-default query, complete, and clear calls return
NLS_JOB_STATUS_NOT_INITIALIZED. - Completing a cancelled binding handle returns
NLS_JOB_STATUS_CANCELLEDand clears the handle. - A completion attempt that cannot reach a terminal state maps to
NLS_JOB_STATUS_FAILEDand leaves the handle set.
Binding structs are plain ABI types holding no STL objects. The native C++ headers are same-toolchain SDK interfaces, not a stable cross-compiler ABI.
The TaskGraph carries render scheduling and engine phase dependencies:
- Ready Any tasks enter the same
JobQueuethroughJobs::Internal::DispatchJob; TaskGraph owns no compute threads or worker queues. The bridge reuses active-group, capacity and shutdown accounting without adding a second JobHandle completion history to the graph's own TaskCompletion state. - Jobs workers use local LIFO queues, an external injection FIFO and cross-worker stealing. Completion observers use a separate condition variable, so finishing a job does not wake idle workers unless runnable work needs them.
- Only
Finalize, after an Any task body and user payload destructors have finished, may retain a single successor on the same worker. Fan-out wakes other workers. Submission inside a task body and named-lane completion keep their normal wakeup behavior, including a parent that submits one child and then blocks. -
TaskGraphBatchvalidates a one-shot DAG before execution;GraphCompletionwaits for all branches, including independent work after failure. -
TaskCompletion::Wait()assists the shared pool on workers and pumps registered named lanes. Self/dependency-stack waits are rejected; user mutex cycles and unpumped named lanes remain caller errors. -
RequestCancelpropagates along the dependency graph and wakes every waiter. - Named Pump requires registration; completion waits and
PumpCurrentThreadservice every named lane owned by the caller. Shutdown waits for running bodies and cancels unstarted orphan-lane work; explicit Start is required after shutdown.
Rendering uses three logical lanes:
| Lane | Responsibility | Query |
|---|---|---|
| Game | Produce commands | IsInGameThread() |
| Render | Consume commands and build the frame | IsInRenderingThread() |
| RHI | Translate and submit native command buffers | IsInRhiThread() |
Render and RHI attach to the TaskGraph once started. In tasks mode the RHI lane is a TLS execution context rather than a fixed OS thread.
Game Thread
EnqueueRenderCommand (strict FIFO serial queue)
| scene proxy add/remove/change, frame render, resize, resource release
v
Render Thread
build the frame, generate commands
|
v
RHI executor
Dispatch (serial intake, assigns a global submission sequence)
Translate (parallel native command buffer generation on workers)
Submit (ordered queue submission, cross-queue semaphores, readback, Present)
The async pipe only carries independent resource preparation and merges it explicitly through dependency events before consumption.
| Layer | Purpose |
|---|---|
FrameResourceRing |
Answers whether the GPU is still using a batch of resources |
FrameLatencyController |
Controls CPU frame latency |
RenderCommandFence |
Render / Rhi / Swapchain sync depths |
Thread names are registered at startup and are visible to profilers. Named entries include the Game Thread, Render Thread, a dedicated RHI Thread, the shared Job Worker <n>, Background Job Worker <n>, and the editor's metadata/import, startup cache, Prefab preparation, shader compile and reflect, file watcher, managed script build, debug endpoint, progress dialog, and trace writer workers.
In tasks mode, RHI work keeps the physical worker's name instead of claiming a dedicated RHI thread.
- Rendering Overview shows how the lanes build a frame.
- Profiling and Graphics Debugging shows how to observe these threads.
Nullus Engine
中文
- 认识 Nullus
- 安装与快速入门
- 使用编辑器
- 场景与对象
- Prefab 工作流
- 资产与内容管线
- 渲染、材质与光照
- 大场景与资源管理
- 游戏逻辑与脚本
- 用户界面
- 动画与角色
- 物理与交互
- 音频、特效与媒体
- AI 与联网
- 平台、构建与发布
- 扩展与引擎架构
- 调试、性能与质量
- 参考手册
- 示例与发展路线
English
- Getting to Know Nullus
- Install and Quick Start
- Using the Editor
- Scenes and Objects
- Prefab Workflow
- Assets and Content Pipeline
- Rendering, Materials, and Lighting
- Large Scenes and Resource Management
- Gameplay and Scripting
- User Interface
- Animation and Characters
- Physics and Interaction
- Audio, Visual Effects, and Media
- AI and Networking
- Platforms, Builds, and Releases
- Extending the Engine
- Debugging, Performance, and Quality
- Reference
- Examples and Roadmap