Skip to content
Projects

genaray/Arch.ZeroAllocJobScheduler

View on GitHub

About

A high-performance alloc free c# Jobscheduler.

Games & Emulation

How these counts are measured

What you can do

  • Jobs as classes or as structs, without boxing
  • Dependencies: a job can wait for any number of other jobs
  • Child jobs: wait for a parent and you wait for its children
  • Parallel-for over ranges, with optional SIMD batches

Measured star growth

in 24h
0
in 7 days
+1
in 15 days
+1
in 1 month
Collecting history

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.md

Original

ZeroAllocJobScheduler Maintenance Nuget License C# Build

A high-performance, allocation-free C# job scheduler for game development and data-oriented programming. It runs the parallel work of Arch, the ECS, but fits any game loop.

  • ๐ŸŽ๏ธ FAST > Work stealing, lock-free queues and cache-friendly data. A small job costs a fraction of a microsecond to schedule and finish!
  • โ™ป๏ธ ZERO ALLOC > Scheduling, waiting, dependencies and parallel-for do not create garbage, and tests make sure it stays that way.
  • ๐Ÿ˜ด POLITE > Idle workers sleep, so your game keeps its CPU for rendering, audio and the rest. No spinning cores!
  • ๐Ÿค BARE MINIMUM > Three calls to remember: Schedule, Flush, Wait. Not bloated, no hidden costs.
  • ๐Ÿงฉ COMPLETE > Dependencies, child jobs, parallel-for, SIMD batches, cancellation and exception handling are included.
  • ๐Ÿšข SUPPORT > Targets .NetStandard 2.1, so it runs on .Net 6 and 8 and may be used with Unity or Godot!

Download the package and get started today!

dotnet add PROJECT package ZeroAllocJobScheduler --version 2.0.0

โฉ Quickstart

Let's say you want to run some work on all your cores... sounds complicated? It's not! Create a scheduler, schedule a job, flush it and wait for it.

using Schedulers;

// A job is a class or a struct
public struct HelloJob : IJob
{
    public void Execute() => Console.WriteLine("Hello from a worker!");
}

using var scheduler = new JobScheduler();           // one worker per processor

var handle = scheduler.Schedule(new HelloJob());    // prepares the job
scheduler.Flush(handle);                            // hands it to the workers
scheduler.Wait(handle);                             // returns when it is done, and helps working meanwhile

[!NOTE] Keep one scheduler for the lifetime of your program. Creating it is the only part that allocates. Jobs can be structs or classes.

๐Ÿ’ก Highlights

That is all you need to start. If you want to know more about the techniques under the hood, read how it works. There's more to explore, for example...

๐Ÿค Our promise

  • Bare minimum - No overengineering, no hidden costs
  • Incredibly fast and allocation free
  • No busy waiting, an idle scheduler uses no CPU
  • Every feature is tested, including stress tests for the threading code

๐Ÿš€ Features

  • Jobs as classes or as structs, without boxing
  • Dependencies: a job can wait for any number of other jobs
  • Child jobs: wait for a parent and you wait for its children
  • Parallel-for over ranges, with optional SIMD batches
  • Cancellation of jobs, including children and dependents
  • Exceptions in jobs do not kill workers, and surface where you wait
  • Safe, recycled handles: old handles are recognized
  • Idle policy that adapts to your machine, and can be replaced
  • And much more...

๐Ÿ”— Dependencies and children

var load = scheduler.Schedule(new LoadJob());
var physics = scheduler.Schedule(new PhysicsJob());
var render = scheduler.Schedule(new RenderJob());
scheduler.AddDependency(render, load);              // render waits for load AND physics
scheduler.AddDependency(render, physics);

scheduler.Flush(load);                              // flush the jobs without dependencies, the rest follows
scheduler.Flush(physics);
scheduler.Wait(render);

var parent = scheduler.Schedule(new ParentJob());
var child = scheduler.Schedule(new ChildJob(), parent);   // waiting for the parent also waits for its children
scheduler.Flush(parent);
scheduler.Flush(child);
scheduler.Wait(parent);

๐Ÿงฎ Parallel-for

using Schedulers.Utils;

public struct Scale : IJobParallelFor
{
    public float[] Data;
    public void Execute(int index) => Data[index] *= 2f;
}

var data = new float[100_000];
var handle = scheduler.ScheduleParallelFor(new Scale { Data = data }, data.Length);
scheduler.Flush(handle);
scheduler.Wait(handle);

Implement IJobParallelForBatch and use ScheduleParallelForBatch to receive Execute(int start, int count) with whole batches, for example to work with SIMD. Like every other handle, the result can be waited for, cancelled and used for dependencies.

๐Ÿ›‘ Cancellation

scheduler.Cancel(handle);                           // skips jobs that did not start, including children and dependents

if (scheduler.IsCancelled(handle)) return;          // lets a running job stop by itself, when it has its handle

๐Ÿ’ฅ Exceptions

try { scheduler.Wait(handle); }
catch (AggregateException e) { /* the exceptions of the jobs that threw */ }

scheduler.JobExceptionHandler = exception => Console.WriteLine(exception);   // or get notified right away

๐Ÿ˜ด Idle workers

Workers without jobs look for work for a short time and then sleep. How long is chosen from the wake-up time of your machine. To override that:

using Schedulers.Idle;

var scheduler = new JobScheduler(0, new FixedIdleSpinPolicy(TimeSpan.FromMilliseconds(0.1)));   // or your own IIdleSpinPolicy

๐Ÿš€ Performance

The scheduler is built for the jobs of a game frame: many small ones, a few big ones, and a lot of parallel-for. Care is taken to find a healthy balance between CPU performance, memory and an idle machine.

Scenario NuGet 1.1.2 Now
20,000 independent jobs 68.8 ms 4.2 ms 16x
One job that waits for 1,000 jobs 5.2 ms 0.35 ms 15x
100 parallel-fors of 2,000 elements, like a frame of queries 10.4 ms 2.0 ms 5x
Parallel-for over 1,000,000 elements 1.8 ms 0.29 ms 6x
Chain of 20,000 dependent jobs 21.4 ms 7.8 ms 2.7x
First job after a pause of 2 ms 250 us 53 us 5x
Allocation for 20,000 struct jobs 480 KB 0
CPU usage while idle 0 0

Measured against the last NuGet release with BenchmarkDotNet on one laptop, so take the numbers as an order of magnitude.

Compared with Parallel.For, Task and the ThreadPool it allocates nothing where they allocate kilobytes to megabytes, and it is faster for large ranges and for many queries at once. It is not faster everywhere: ThreadPool work items are a bit faster for 1,000 empty jobs, and Task.ContinueWith chains that run inline beat a short chain of dependent jobs.

Have a look at the benchmarks for all scenarios, and how they were measured!

๐Ÿ“– Documentation

  • ๐Ÿ” How it works > What happens to a job, and why it is fast.
  • ๐Ÿ“Š Benchmarks > Every scenario, compared with the last NuGet release.

โš ๏ธ Good to know

  • At most 65,535 jobs can be scheduled and unfinished at the same time.
  • Handles are recycled once their job has finished. Using an old handle is safe: waiting for it returns at once, cancelling it does nothing and flushing it throws.
  • Wait also executes jobs on the calling thread, which may include jobs you did not wait for.
  • Running jobs are never interrupted, cancellation is cooperative.
  • The tests and benchmarks ran on Linux x64 with .Net 8 so far. ARM64 and Windows are not covered yet.
  • IParallelJobProducer and ParallelJobProducer<T> still work but are obsolete. Use IJobParallelForBatch instead.

๐Ÿ› ๏ธ Contributing

Found a bug, or have an idea? Open an issue or a pull request! The solution contains the tests (JobScheduler.Test) and the benchmarks (JobScheduler.Benchmarks, and JobScheduler.Benchmarks.Baseline for the NuGet package). Please run the tests before you send a pull request, they include stress tests for the threading code. Every push is built and tested on Linux, Windows and macOS. A pull request with the label benchmark also runs the benchmarks. A release is made by starting the workflow by hand: enter the version and the release notes, and choose to publish. It pushes the package to NuGet and GitHub, and creates the GitHub release.

๐Ÿ“„ License

Apache 2.0, see LICENSE.

Explore related projects

Loadingโ€ฆ