Skip to content

Threading ​

World, pools and filters are single-threaded. Reading RawData/RawEntities of pools from several threads is safe only while no structural change (Add/Remove/Create/Destroy) happens on any thread. Component type registration (ComponentType<T>.Index) is thread-safe.

ParallelRunner ​

Data-parallel work over a filter or group without delegates or per-call allocations. A job is a struct implementing IRangeJob. Run takes it by value and keeps one copy of it, without boxing; every worker and the calling thread execute that same copy. A field the job writes is therefore shared by all threads and never reaches the struct passed to Run: keep results in component data, or in an array the job references and indexes by its range.

csharp
struct MoveJob : IRangeJob {
    public Filter Filter;
    public ComponentPool<Position> Positions;
    public ComponentPool<Velocity> Velocities;

    public void Execute(int start, int end) {
        var entities = Filter.Entities;
        for (int i = start; i < end; i++) {
            int e = entities[i];
            Positions.Get(e).X += Velocities.Get(e).X;
        }
    }
}

Create the runner once, run the job every frame, dispose the runner on shutdown:

csharp
class ParallelMovementSystem : IInitSystem, IRunSystem, IDestroySystem {
    ParallelRunner _runner;
    Filter _moving;
    ComponentPool<Position> _positions;
    ComponentPool<Velocity> _velocities;

    public void Init(World world, SharedData shared) {
        _runner = new ParallelRunner();          // ProcessorCount - 1 workers; pass 0 for inline execution
        _moving = world.Filter().Inc<Position>().Inc<Velocity>().End();
        _positions = world.Pool<Position>();
        _velocities = world.Pool<Velocity>();
    }

    public void Run(World world) {
        _runner.Run(new MoveJob { Filter = _moving, Positions = _positions, Velocities = _velocities }, _moving.Count, chunkSize: 512);
    }

    public void Destroy(World world) {
        _runner.Dispose();                       // stops the worker threads
    }
}

The range [0, count) is split into chunks of at most chunkSize indices (default 1024), handed out dynamically to the workers and the calling thread, so uneven work balances itself. After the first Run for a job type, Run allocates nothing.

Workers ​

ParallelRunner starts its own dedicated System.Threading.Thread workers (background threads named KenseiECS worker N) in the constructor; it does not use the .NET thread pool or the Unity job system. new ParallelRunner() creates Environment.ProcessorCount - 1 workers; new ParallelRunner(n) creates n. WorkerCount reports the number. The calling thread always works too.

When Run executes inline

Run calls job.Execute(0, count) directly on the calling thread, without waking any worker, when:

  • the runner has 0 workers — new ParallelRunner(0), or the default constructor on a single-core machine (use 0 workers on platforms without threads, such as WebGL), or
  • count <= chunkSize.

count <= 0 returns immediately.

Groups ​

For a group, index Data1/Data2 from start to end:

csharp
struct MoveGroupJob : IRangeJob {
    public Group<Position, Velocity> Group;

    public void Execute(int start, int end) {
        var pos = Group.Data1;
        var vel = Group.Data2;
        for (int i = start; i < end; i++) {
            pos[i].X += vel[i].X;
            pos[i].Y += vel[i].Y;
        }
    }
}
csharp
runner.Run(new MoveGroupJob { Group = group }, group.Count);   // chunkSize defaults to 1024

Rules for jobs ​

  • Jobs may read and write component data of the entities in their range and nothing else: no structural changes, no listeners, no filter or group registration.
  • A job's own fields are read-only inputs: all threads execute one copy of the struct, so a field written in Execute (a counter, a sum) is a data race, and its value is not returned to the caller.
  • Modify and MarkChanged of a change-tracking pool may be called in a job for the entities of its range. The world's change counter is incremented without synchronization, so two workers can give their components the same version, and a worker that read the counter late can leave it below versions other workers handed out: a component written in the job can then show as changed against a bookmark taken after the job. No write is lost, also across the counter's wrap: a version ahead of the counter counts as the newest, the aging of old versions never overwrites a fresh one, and at the first wrap one worker ages the old versions while the others wait before they store a version of the new turn.
  • Two jobs must not run at the same time on one runner.
  • An exception in a worker is rethrown by Run on the calling thread once every worker stopped; the chunks not yet started are skipped.
  • Dispose the runner on shutdown: Dispose() stops the worker threads, and Run on a disposed runner throws ObjectDisposedException.

Changed in 2.5.0

Up to 2.4.0 the counter went negative at its wrap (see Counter wrap). The handling of the wrap that replaces it also covers versions written by jobs, as described above.