EasyEcs

Threading and parallel systems

How EasyEcs uses every core without locks on hot paths: one owner thread per world, parallel stages of non-conflicting systems and parallel [ForEach].

A server has many cores and a lot of entities. EasyEcs spreads the work three ways, none of which needs a lock on a hot path: one world per thread (a world per zone or map, each owned by its thread), parallel systems (inside one update, systems whose access does not conflict run at once) and parallel [ForEach] (one heavy method split into chunks of rows). The generator writes each system's read and write sets from its parameters, so the scheduler, not discipline, decides what may run together, and the analyzer rejects what could race.

When to use it

Use it for

One world per thread for a server with several zones, maps or matches. ParallelSystems for several heavy, independent systems in one world. [ForEach(Parallel = true)] for one method over tens of thousands of rows.

Skip it for

Several threads of your own changing one world: structural changes belong to its owner thread (EECS014 reports the ones it sees). Parallel systems or methods over a few hundred rows: the hand-off to the thread pool costs more than the work.

How to use it

Terms: process, world, owner thread

TermMeaning
ProcessYour server. It holds any number of worlds; they share nothing but type indices.
WorldOne isolated set of entities, components, singletons and systems (new World()).
Owner threadThe thread that calls world.Update() and touches the world's data. One at a time per world.
Parallel stageInside one Update(), systems with no order and no conflict between them, run on thread-pool threads with the owner taking part. Ownership does not change.

Worlds share nothing, so a server that splits its entities over several worlds, each owned by one thread, needs no synchronization at all.

Thread 1

World: zone 1

Thread 2

World: zone 2

Thread N

World: zone N

public static class Zones
{
    // A world per thread: each thread owns its world, nothing is shared.
    public static Thread[] Start(World[] worlds)
    {
        var threads = new Thread[worlds.Length];
        for (int i = 0; i < worlds.Length; i++)
        {
            var zone = worlds[i];                                   // one variable per iteration
            threads[i] = new Thread(() => { for (int t = 0; t < 1_000; t++) zone.Update(); });
            threads[i].Start();
        }

        return threads;
    }
}

The MultiWorld sample runs this layout and prints entity-updates per second. To move a player to a zone of another thread, hand it across as bytes: the source's owner writes the group with SaveEntities and posts the bytes to a queue the target's owner drains, which calls LoadEntities. MoveEntities is only for two worlds owned by the same thread.

Order of systems

Update() runs systems in registration order, with each system that carries [UpdateBefore<T>] / [UpdateAfter<T>] moved just before or after T. Systems never call each other: a system that consumes what another produces is registered after it or says [UpdateAfter<Producer>]. Structural changes apply at once, so a later system of the same update already sees an entity an earlier one created, destroyed or tagged: there are no command buffers to play back. Whatever runs in parallel, the result of an update equals running the systems one by one in that order.

Parallel systems

With WorldOptions.ParallelSystems = true, systems with no order and no conflict between them run at the same time. Each system's access comes from its [ForEach] parameters:

[ForEach] parameterDeclares
ref T component or singletonwrites T
in T component or singletonreads T
[With<T>], [Without<T>], [WithAny<T>]nothing (filters read presence, which no parallel system changes)
[Changed<T>], [Removed<T>]reads T (its change ticks)
Entity or World, an instance method, an OnUpdate overrideruns alone
no [ForEach] method at allruns alone

Two systems conflict when one writes something the other reads or writes, or when either runs alone. A system goes to the stage after the latest one holding a system it must follow (by an ordering, or by an earlier system it conflicts with). Stages run one after another; the systems of a stage run at once.

public record struct Body(float X, float Y, float Vx, float Vy) : IComponent;
public record struct Vitals(int Health, int Max) : IComponent;
public record struct Alarms(int Count) : ISingletonComponent;

public class MoveBodies : EcsSystem        // writes Body
{
    [ForEach] static void Move(ref Body b) { b.X += b.Vx; b.Y += b.Vy; }
}

public class RegenerateHealth : EcsSystem  // writes Vitals
{
    [ForEach] static void Regenerate(ref Vitals v) => v.Health = Math.Min(v.Health + 1, v.Max);
}

public class LowHealthAlarm : EcsSystem    // reads Vitals: conflicts with RegenerateHealth
{
    [ForEach] static void Count(in Vitals v, ref Alarms alarms) { if (v.Health < 10) alarms.Count++; }
}

stage 2

stage 1: at once

MoveBodies

RegenerateHealth

LowHealthAlarm

using var parallel = new World(new WorldOptions { ParallelSystems = true });
parallel.AddSingleton<Alarms>();
parallel.AddSystem<MoveBodies>();
parallel.AddSystem<RegenerateHealth>();
parallel.AddSystem<LowHealthAlarm>();
parallel.Update();                          // stage 1 on two threads, then stage 2

The runner allocates nothing: the calling thread works through a stage with up to MaxDegreeOfParallelism - 1 reusable thread-pool work items. Lower MaxDegreeOfParallelism when several worlds or IO threads share the cores:

using var zone = new World(new WorldOptions { ParallelSystems = true, MaxDegreeOfParallelism = 4 });

The first exception of a stage is rethrown on the calling thread after the stage; with WorldOptions.SystemErrors = SystemErrorPolicy.Disable, a failing system is switched off with its exception in system.Error instead.

Parallel [ForEach] methods

[ForEach(Parallel = true)] splits one method's rows into chunks across threads. It must make no structural change, run per entity and write no singleton (EECS010):

public record struct Regen(int PerTick) : ISingletonComponent;

public class RegenerateAll : EcsSystem
{
    [ForEach(Parallel = true), Without<Dead>]
    static void Regenerate(ref Health hp, in Regen regen) => hp.Value += regen.PerTick;   // reads the singleton only
}

Parallel systems and parallel methods compose: inside a parallel stage, a parallel method whose runner is busy with another system's method runs on its own thread instead of waiting.

Input from other threads

A world has one owner thread, and EasyEcs adds no cross-thread queue of its own: structural changes are immediate on that thread, so there is nothing to defer. Input from other threads (network, timers, a database) goes through a queue you own, and a system on the owner thread turns it into data:

using System.Collections.Concurrent;

public record struct MoveRequest(int PlayerId, float X, float Y);           // a message, not a component
public record struct MoveIntent(int PlayerId, float X, float Y) : IComponent;

public sealed class ReceiveMoves(ConcurrentQueue<MoveRequest> inbox) : EcsSystem
{
    private readonly ConcurrentQueue<MoveRequest> _inbox = inbox;          // filled by the network threads

    protected override void OnUpdate()
    {
        while (_inbox.TryDequeue(out var move))
            World.CreateEntity(new MoveIntent(move.PlayerId, move.X, move.Y));   // input becomes data
    }
}

Register it with world.AddSystem(new ReceiveMoves(inbox)) before the systems that consume MoveIntent. The queue's type, bound and back-pressure are your choice. Keep the queue in a readonly field of the system that drains it (EECS007 allows it), not in a singleton: World.Save writes every singleton, and a managed queue would need a formatter. The GameLoop sample drains a mailbox from a network thread this way.

What the world synchronizes

OperationSafety
Structural changes, systems and singletons added or removed, Capture / Restore, Save / LoadOwner thread only, one at a time. A plain owner flag (no atomic instruction): one started while another runs, or while the structure is frozen (a parallel stage, a parallel [ForEach], a batch job, an INoStructuralChanges pass), throws InvalidOperationException instead of tearing the tables.
Query matching, Has, Get lookupsLock-free over immutable, copy-on-write table lists. The first use of a query shape takes a compare-and-swap gate once.
A singleton a system adds with GetOrAddSingleton<T>() / GetOrAddX()The same gate: systems of one stage may add it at once.
Component and singleton valuesNot synchronized, by design: the owner thread or the scheduler decides who touches them.
Value indexes, and the unlinking done by destroys and removalsOwner thread only while the world has an index.

What catches a change made off the owner thread:

Where the change comes fromCaught by
A [ForEach] method without Entity or World changing structure through a handle it holdsEECS013 at compile time; the runtime throws in a parallel stage
A system of a parallel stage, or a parallel job, changing structure through a helperThe runtime: the structure is frozen, every structural change throws
A lambda handed to Task.Run, Parallel.*, ThreadPool, new Thread or new Timer changing a world the code around it also changesEECS014 at compile time
Your own threads in any other wayNothing reliable: hand the change to the owner as data

Every structural call counts here, including the less obvious ones: entity.Run<…>(ref job) (a job may change structure) and LoadEntitiesInto belong to the owner thread too, and the analyzer treats them as structural (EECS010, EECS014).

Full example

A hundred thousand units steer towards a target, move and regenerate: the steering method splits its rows over several threads, and the regeneration system shares a stage with it because the two touch different components. Put the files in a console project that references EasyEcs (dotnet add package EasyEcs) and run it with dotnet run.

It prints:

unit 0 at (7.06, 7.06) with 60 hp

The result is the same as running the three systems one by one in registration order: a parallel stage never changes what an update computes, only how many threads compute it.

How to use it fast

  • Prefer worlds to parallel stages. Worlds on their own threads scale with no hand-off at all; a stage pays a thread-pool hand-off per update.
  • Turn ParallelSystems on for heavy systems only, ones that iterate thousands of entities.
  • Split by data, not by method. Two systems that write different components run together; one that writes everything runs alone.
  • Read with in. A ref that only reads declares a write, and a write conflicts (EECS025 reports it).

One world of 100,000 entities, and the same entities in four worlds on four threads (WorldSimulationBenchmark, MultiWorldBenchmark): 1.72 ms per tick in one world, 924 μs for the four worlds together.

BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Four independent systems over 100,000 entities, sequential and parallel (ParallelSystemsBenchmark), and one method over 100,000 rows, sequential and parallel (ParallelForEachBenchmark):

CaseParallelMeanvs baselineAllocated
TickFalse420 μs—0 B
TickTrue295 μs—0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.
CaseParallelMeanvs baselineAllocated
TickFalse1.68 ms—0 B
EntityJobFalse1.92 ms—0 B
TickTrue884 μs—0 B
EntityJobTrue896 μs—0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

What it costs

  • One world, one thread: no locks, no atomics on hot paths; a structural change checks and sets a plain flag.
  • A parallel stage: a hand-off to reusable thread-pool work items, nothing allocated; the ParallelSystemsBenchmark table above shows what it saves on heavy systems.
  • A parallel method: the same runner, over chunks of rows; the calling thread always takes part.
  • Off: ParallelSystems is off by default, and a world that never uses it pays nothing for it.

Pitfalls

MistakeWhat happensCaught by
A structural change inside a parallel methodChunks on other threads would tear the tablesEECS010
A ref singleton in a parallel methodChunks race on one valueEECS010
Changing a collection through an in parameterScheduled as a read: races with parallel readersEECS011
A structural change through a held handle in a method that takes no EntityThe system shares a stage it should notEECS013
Task.Run(() => world.CreateEntity(...)) beside the ownerTwo threads change one worldEECS014
A ref parameter that only readsDeclares a write: fewer systems run togetherEECS025

Compared with other ECS libraries

LibraryOrder of systemsSystems in parallelHow conflicts are avoided
EasyEcsRegistration order, [UpdateBefore<T>] / [UpdateAfter<T>]Systems with no order and no conflict; one method's rows in chunksAccess generated from ref / in; the analyzer rejects parallel methods that could race
ArchYour call order (Arch.System: group order)Within one query (ParallelQuery)You keep query bodies independent
Friflo.Engine.ECSSystemRoot / SystemGroup orderWithin one query (RunParallel)You keep query bodies independent
DefaultEcsSequentialSystem orderParallelSystem (all children at once), per-set runnersYou put only independent systems in a ParallelSystem
Bevy (Rust)Ambiguous unless orderedAny systems whose access does not conflictAccess read from parameter types
Unity DOTSUpdateBefore / UpdateAfter in groupsJobsRead/write handles and the job safety system

EasyEcs takes the access-based model of Bevy and Unity DOTS, and keeps the order total and deterministic. Measured against the parallel runners of the others:

Four independent systems over 100,000 entities, sequential and parallel

  • EasyEcs
  • Other libraries
EasyEcs (Parallel=False)0 B allocated395 μsDefaultEcs (Parallel=False)1.19× · 0 B allocated471 μsEasyEcs (Parallel=True)0 B allocated370 μsDefaultEcs (Parallel=True)1.09× · 0 B allocated405 μs0.00 ns100 μs200 μs300 μs400 μs500 μsTime (shorter is faster)

BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Data table
LibraryParallelMeanvs EasyEcsAllocated
EasyEcsFalse395 μs1.00×0 B
DefaultEcsFalse471 μs1.19×0 B
EasyEcsTrue370 μs1.00×0 B
DefaultEcsTrue405 μs1.09×0 B

100,000 agents steering on all cores

  • EasyEcs
  • Other libraries
EasyEcs: Parallel0 B allocated766 μsFriflo.Engine.ECS: QueryJob0.98× · 0 B allocated754 μsArch: InlineParallelQuery0.89× · 0 B allocated685 μsDefaultEcs: ParallelRunner1.11× · 0 B allocated854 μs0.00 ns200 μs400 μs600 μs800 μsTime (shorter is faster)

BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Data table
LibraryCaseMeanvs EasyEcsAllocated
EasyEcsParallel766 μs1.00×0 B
Friflo.Engine.ECSQueryJob754 μs0.98×0 B
ArchInlineParallelQuery685 μs0.89×0 B
DefaultEcsParallelRunner854 μs1.11×0 B
Edit on GitHub

Last updated on

How is this guide?

On this page