Skip to main content
Version: Next

TaskGraph and the Three Thread Boundaries: When to Parallelise, When to Queue

Multithreading problems in UE rarely crash. They show up as "occasional weirdness": one frame where a mesh vanishes, data that disagrees once in a while, a 20 ms hitch while uploading a texture. The common root is code running on a thread it does not belong to, and the compiler will never tell you.

Thread names and APIs follow the stable UE5 shape; concrete task queues and parallelism settings vary by platform and version. Check TaskGraphInterfaces.h and RenderingThread.h in the version you build.

Three threads, three sets of permissions​

ThreadMay touchMust never touchUsual entry point
Gameall UObjects, world state, GClong blocking workTick, Blueprints, gameplay
Renderscene proxies (FPrimitiveSceneProxy), render resource descriptionsUObjects (GC cannot see them), world stateENQUEUE_RENDER_COMMAND
RHIcommand list submission, the graphics APIany game objectthe RHI command queue
TaskGraph workerpure data computationunlocked shared containers, UObject lifetimeParallelFor, UE::Tasks

The rule of thumb: whoever owns the data is the only one allowed to write it. A render-thread function holding an AActor* is not "forbidden", it is "unable to know when the actor is collected".

Three traps in ENQUEUE_RENDER_COMMAND​

This is the most common cross-thread entry point and where most bugs concentrate.

// anti-pattern: capturing a raw UObject pointer
ENQUEUE_RENDER_COMMAND(UpdateTint)(
[this, Material](FRHICommandListImmediate& RHICmdList)
{
// by the time the render thread runs this, the object may be gone;
// GC cannot see this capture either
Material->SetVectorParameterValue(TEXT("Tint"), Color);
});
TrapConsequenceCorrect approach
capturing a raw UObject*dangling pointer, rare crashesextract plain data (FVector4, handles) on the game thread first
capturing this (actor or component)samecapture values only, or a weak pointer checked before enqueueing
assuming it is synchronousthe next line reads stale stateFlushRenderingCommands() or FRenderCommandFence
check() on game-thread state inside the render threadrandom assertion failuresonly assert IsInRenderingThread() there

The correct shape is extract the data, then enqueue:

void UVMTintComponent::PushTintToRender(const FLinearColor& InColor)
{
// game thread: sample only, never dereference across the boundary
const FVector4 Packed(InColor.R, InColor.G, InColor.B, InColor.A);
TWeakPtr<FSceneProxyRef, ESPMode::ThreadSafe> WeakProxy = ProxyRef;

ENQUEUE_RENDER_COMMAND(UpdateTint)(
[WeakProxy, Packed](FRHICommandListImmediate&)
{
if (auto Pinned = WeakProxy.Pin())
{
Pinned->SetTint(Packed); // touches render-side data only
}
});
}

When you must wait: fences, not sleep​

Render commands are asynchronous. To confirm work actually completed, use a fence; Sleep only destroys the frame rate.

FRenderCommandFence Fence;
Fence.BeginFence(); // called on the game thread, marks an insertion point
Fence.Wait(); // blocks until that point executes; use sparingly
Fence.IsFenceComplete(); // the more common non-blocking poll
ScenarioUseNote
Screenshot / pixel readbackFRenderCommandFence with pollingdo not Wait() inside Tick
Releasing a render resourceBeginReleaseResource + fencerelease must also be queued to the render thread
Level transitionFlushRenderingCommands()a visible hitch; loading screens only
Per-frame syncdo not syncredesign so it takes effect next frame

ParallelFor: the win is granularity, not core count​

ParallelFor splits [0, Count) into chunks across workers. It fits pure data, no shared writes, uniform per-item cost loops.

ParallelFor(Particles.Num(), [&Particles](int32 Index)
{
// writes only Particles[Index], allocates nothing, locks nothing
Particles[Index].Velocity += Gravity * DeltaTime;
});
MisuseSymptomCause
SpawnActor inside the loopcrash or corrupted world stateonly the game thread may mutate the world
tens of nanoseconds per itemslower than serialtask splitting and sync overhead exceed the win
adjacent elements sharing a cache lineslower on more coresfalse sharing; pad or process by blocks
new / TArray::Add insideintermittent crashesallocator and containers are not thread-safe
capturing references used asynchronouslydangling referenceParallelFor blocks, but flagged variants may leave tasks running after return

A useful threshold: measure before parallelising any loop whose body costs less than 10 microseconds. Parallelisation has a non-trivial fixed cost.

How to verify data races​

Never rely on "looks fine". Three techniques, cheapest first:

TechniqueWhat it doesWhat it catches
check(IsInGameThread())asserts the thread at a key entrycallers on the wrong thread (the most common case)
check(IsInRenderingThread())same, render sidegameplay calls from render command bodies
TSan (ThreadSanitizer)compile-time instrumentation, runtime reportsunlocked shared writes, with two call stacks
Stress test with forced serial executionrun ParallelFor single-threaded as a controlordering problems introduced by parallelism

TSan is the highest-value investment: it turns "occasional" into "reproducible error", but requires recompiling whole modules, so it usually lives on a dedicated performance branch.

The seam with async loading​

Which thread an FStreamableManager completion callback lands on depends on the loading entry point you used, not on an "always the game thread" guarantee. Do not assume — assert once:

RequestAsyncLoad(Paths, FStreamableDelegate::CreateLambda([this]()
{
check(IsInGameThread()); // if not, this line tells you immediately
OnAssetsReady();
}));

If the assertion fires, the callback for that path runs elsewhere, and every UObject access must be marshalled back first:

AsyncTask(ENamedThreads::GameThread, [this]() { OnAssetsReady(); });

Checklist​

  1. Which thread owns the data this line mutates? Read-only outside the owner, never write.
  2. Does the cross-thread payload carry values or pointers? Pointers must be thread-safe weak references.
  3. Is any UObject touched inside a render command? Extract the data.
  4. Is the sync really necessary? Prefer "takes effect next frame".
  5. Does the parallel loop allocate, lock, or write neighbouring elements?
  6. Are there thread assertions at the key entries? Adding one is far cheaper than debugging a crash later.