🔀 The Ultimate Multi-Threading Starter Pack (C# version) (GD Script version coming soon)

In this tutorial, we will build a system that will turn your project into a multi threading power house. Rather than feeling tentative and uncertain about using multi threading, it will leave you feeling like you know exactly how to use it and exactly how it works. This system is:

-simple
-easy to understand
-easy to expand, mod and customize
-removes the ambiguity
-easy to debug

That being said, this is not a beginner tutorial.
And now, without further ado, I give you:

The Ultimate Multi-Threading Starter Pack (for C#)

STEP ONE - A quick refresher of multi threading difficulties:

- Race conditions - Two threads access shared data at the same time: unpredictable results.

- Deadlocks - Two threads each hold a lock the other needs: both freeze forever.

- Starvation - One thread never gets access to a resource because others hog it.

- Context switching overhead - CPU wastes time switching between threads instead of doing real work.

- Debugging difficulty - Threads interleave unpredictably, bugs are ambiguous and hard to reproduce.

We need a system that prevents these from happening.

STEP TWO - The basic plan

With this system, to have a thread do some work off of the main thread all you do is this:

  1. Create a job
  2. add it to the job queue

We will start with a dedicated IO Thread. The reason why we do this is because, for our needs the most effective strategy, will be to treat the hard drive as though it can only do one thing at a time (read or write) regardless of thread count (see note below). If multiple threads try to perform IO operations at the same time your operating systems I/O scheduler will try to make everyone happy by doing a funny little dance going back and forth between tasks and it will only slow down performance.

Side Note: The IO Thread and the JobScheduler are nearly identical and totally seperate. You might think its a good idea to combine them. Its not. It only adds complexity with no benefit.

A note about modern hard drives

Another forum member pointed out to me that modern hard drives are capable of multiple simultaneous IO operations which can be accessed via C#'s async / await tool set. However utilizing that capability is a bit more complicated and will not be covered in this tutorial. For the majority of solo developers this is most likely over kill. Your game would have to have insane amounts of data throughput before you would ever feel the need.

It is true, that in the olden days (and even today), hard drives - the ones with spinning silver platters inside - can indeed only read or write one thing at a time. However this limitation does not exist for SSDs. And in fact, even regular old SATA hard drives are able to internally queue up up to 32 operations. And then reorder them to get them all done faster.

For modern NVMe SSD drives the queue sizes are even (ridiculously) larger - 65K queues of 65K operations each. Which is to say - these drives will HAPPILY perform multiple operations at the same time, and, in fact, that’s how they work best. Reading one bit takes a fixed amount of time, but the more bits you can read in parallel, the faster you can get things done.

To leverage this, modern operating systems offer “Asynchronous I/O” (aka “non-blockng I/O”) capabilities - in essence, you start your read or write operations, but don’t wait for them to complete. Your read()/write() function calls return immediately with a “pending” status and some sort of “operation ID” that you can later use to check the status of the operation. This way you can issue multiple read/write requests in parallel, and the OS/drive will take care of arranging the operations in a way that makes them complete the fastest.

Note - you technically don’t even need to spin up a separate I/O thread for this. The whole “in parallel” business happens in the OS/hardware. You just periodically check whether your read operation has completed (or there might be a callback mechanism provided by the OS).

STEP THREE - checklist

we need:

  • IOThread (a class)

  • IOJob (an interface for the template and classes for the specific jobs)

  • IOJobResult class (optional: for logging / debugging / performance monitoring)

  • JobScheduler (class)

  • WorkerThread (class)

  • Job (an interface for the template and classes for the specific jobs)

  • JobResult class(optional)

STEP FOUR - Implementation

IO Thread

using Godot;
using System;
using System.Collections.Concurrent; // <<<<<<<<<<
using System.Threading;              // <<<<<<<<<<
namespace DBTS.IO;

/// I am creating this as an autoload which is why it inherits Node
public sealed partial class IOThread : Node {
    
    /// So we instantiate the IOThread as "I" so that it can be accessed
    /// from anywhere else in the codebase with:
    /// IOThread.I
    public static IOThread I { get; private set; }

    private Thread thread; // the actual thread

    /// The job queue. Must be a blocking collection.
    private readonly BlockingCollection<IOJob> IOJobQueue = new();



    public override void _Ready() {
        /// Instantiate self as IOThread.I
        I = this;

        /// Spin up the IOThread
        thread = new Thread(IOLoop) {Name = "IO", IsBackground = false};
        thread.Start();
    }


    /// The IO thread is asleep.
    /// The blocking collection wakes this thread up when an job is added.
    private void IOLoop() {
        /// It tries to dequeue a job from the JobQueue.
        foreach (var IOJob in IOJobQueue.GetConsumingEnumerable()) {
            /// It processes the job.
            ProcessIOJob(IOJob);
        }
        /// If there's nothing left in the job queue, it goes back to sleep.
    }


    /// All other systems in the game can add a job to the IO job queue with:
    /// IOThread.I.Enqueue(job);
    public void Enqueue(IOJob job) {
        /// if you later on want to sort jobs by priority,
        /// this is where you'd do it
        IOJobQueue.Add(job);

    }


    private void ProcessIOJob(IOJob job) {
            job.PerformJob();
    }


    /// <summary>
    /// Blocks the calling thread until this thread fully terminates. <br/>
    /// Call on shutdown
    /// </summary>
    public void Shutdown() {
        IOJobQueue.CompleteAdding();
        
        if (thread != null && thread.IsAlive)
            thread.Join();
    }

Important notes about BlockingCollection

The blocking collection is a special data structure that does a lot more than you probably think.

It does two things: it serves as a data container that is safe to access by multiple threads (called a concurrent queue), but it has the added functionality of waking a thread when an item is added. This might sound simple but it’s absolutely critical and it solves one of the core, hidden, difficulties of multi-threading : the 'producer-consumer problem '

If you were to use a ConcurrentQueue instead:

  1. You add a job to the job que ue

  2. You manually wake up a thread to get to w ork

  3. You get a null reference e rror

Because the thread woke up instantly, and tried to dequeue a job before the job was finished being added to the q ueue.

Yes. You read that right. And to make matters worse, it doesn’t happen every time, it will sometimes work.

On a microscopic timescale, adding an item to a Queue is sometimes slower than waking a thread. So even though adding the job to the job queue came first, the thread woke up, found nothing there, and threw an error. This micro-managing of threads is called thread signaling and its a low-key nightmare.

TLDR: YOU MUST USE A BLOCKING COLL ECTION

IOJob

using System;
using System.Collections.Concurrent;
using DBTS.MemTools;
using DBTS.Threading;

namespace DBTS.IO;

    public enum IOJobCategory { Saving, Loading } /// add whatever categories you want

    public enum IOJobPriority { High, Normal } /// do whatever you want bro


///////////////////////////////////////////////////////////
/////////////// IOJob Interface ///////////////////////////
////// Acts as a template for all IOJobs //////////////////
//// All IOJobs must have these fields and functions //////
/////////// (but can also have more) //////////////////////
///////////////////////////////////////////////////////////
public interface IOJob {
    public IOJobCategory Category { get; set; }
    public IOJobPriority Priority { get; set; }
    public DateTime EnqueuedAt { get; set; }

    public void PerformJob() { }
}


///////////////////////////////////////////////////////////
/////////////// Specific Jobs /////////////////////////////
/////////// That you will hard code ///////////////////////
///////////////////////////////////////////////////////////

/// an example job:

public class LoadGameSettings : IOJob {
    /// necessary fields to satisfy IOJob interface
    public IOJobCategory Category { get; set; }
    public IOJobPriority Priority { get; set; }
    public DateTime EnqueuedAt { get; set; }

    /// custom field for this specific job
    public string filePath;


    /// This is the constructor for the specific Job
    public LoadGameSettings(string filePath){
        Category = IOJobCategory.Loading;    // hard code the category
        Priority = IOJobPriority.Normal;     // hard code the priority
        EnqueuedAt = DateTime.UtcNow;        // DateTime will be the instant
                                                 // it was created
        this.filePath = filePath;
    }   

    public PerformJob() {
        // Do your IO work
        RunTimeFileSystem.LoadGameSettings(filePath);
    }
}

JobScheduler

using Godot;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace DBTS.Threading;

public sealed partial class JobScheduler : Node {

    public static JobScheduler I { get; private set; }
    private readonly List<WorkerThread> Workers = new();
    private readonly BlockingCollection<Job> JobQueue = new();

    public int WorkerCount { get; }

    public override void _Ready() {
        I = this;

        /// Thread 1 = Main
        /// Thread 2 = IO
        /// Threads 3+ = workers
        int WorkerCount = System.Environment.ProcessorCount - 2; 

        WorkerCount = Math.Max(1, WorkerCount);

        /// Create the worker threads
        for (int i = 0; i < WorkerCount; i++) {

            /// We havent created the worker class yet.
            /// This will make more sense in a minute
            Workers.Add(new WorkerThread(
                name: $"Worker-{i}",
                jobQueue: JobQueue
            ));
        }
    }

    /// Same as with the IOThread.
    /// Any system can add a job to the JobQueue with
    /// JobScheduler.I.Enqueue(job)

    public void Enqueue(Job job) {
        JobQueue.Add(job);
    }


    /// <summary>
    /// Stops all workers but allows them to complete their current work
    /// first. Call on shutdown.
    /// </summary>
    public void Shutdown() {
        JobQueue.CompleteAdding();

        foreach (WorkerThread worker in Workers)
            worker.WaitForCompletion();
    }

WorkerThread

using System.Threading;
using System.Collections.Concurrent;

namespace DBTS.Threading;

public sealed class WorkerThread {
    private readonly Thread thread;
    private readonly BlockingCollection<Job> JobQueue;

    public string Name { get; }


    public WorkerThread(string name, BlockingCollection<Job> jobQueue) {
        Name = name;
        JobQueue = jobQueue;
        thread = new Thread(WorkerLoop) {Name = name, IsBackground = false};
        /// Note about isBackground:
        /// Foreground threads will keep the program running.
        /// Background threads are terminated abruptly when the program
        /// closes. 
        /// For a general purpose worker thread its probably best to keep
        /// isBackground = false

        thread.Start();
    }

    /// The thread is asleep by default
    private void WorkerLoop() {
        /// When an item is added to the BlockingCollection, a thread
        /// is woken up
        foreach (var Job in JobQueue.GetConsumingEnumerable()) {
            ProcessJob(Job);
        }
        /// When theres nothing left in the job Queue
        /// the thread goes back to sleep
    }


    private void ProcessJob(Job job) {
        job.PerformJob();
    }

    /// <summary>
    /// This get called by the job scheduler during shutdown. <br/>
    /// Blocks the calling thread until this thread fully terminates.
    /// </summary>
    public void WaitForCompletion() {
        if (thread != null && thread.IsAlive)
            thread.Join();
    }

Job (nearly identical to IOJob)

using System;
using System.Collections.Concurrent;
using DBTS.MemTools;
using DBTS.Threading;

namespace DBTS.IO;

    public enum JobCategory { Chunking, Generation, Pathfinding }

    public enum JobPriority { High, Normal }


///////////////////////////////////////////////////////////
///////////////// Job Interface ///////////////////////////
////// Acts as a template for all Jobs ////////////////////
////// All Jobs must have these fields and functions //////
/////////// (but can also have more) //////////////////////
///////////////////////////////////////////////////////////
public interface Job {
    public JobCategory Category { get; set; }
    public JobPriority Priority { get; set; }
    public DateTime EnqueuedAt { get; set; }

    public void PerformJob() { }
}


///////////////////////////////////////////////////////////
/////////////// Specific Jobs /////////////////////////////
/////////// That you will hard code ///////////////////////
///////////////////////////////////////////////////////////

/// an example job:

public class ExampleJob_Pathfind : Job {
    /// necessary fields to satisfy IOJob interface
    public IOJobCategory Category { get; set; }
    public IOJobPriority Priority { get; set; }
    public DateTime EnqueuedAt { get; set; }

    /// custom field for this specific job
    public Vector2 coordinatesA;
    public Vector2 coordinatesB;

    /// This is the constructor for the specific Job
    public ExampleJob_Pathfind(Vector2 coordinatesA, Vector2 coordinatesB){
        Category = JobCategory.Pathfinding;  // hard code the category
        Priority = IOJobPriority.Normal;     // hard code the priority
        EnqueuedAt = DateTime.UtcNow;        // DateTime will be the instant
                                               // it was created
        this.coordinateA = coordinatesA;
        this.coordinateB = coordinatesB;
    }

   
    public PerformJob() {
        
        Pathfinder.AStar(gridCoordinateA, gridCoordinateB);
    }
}

If you just copy and paste all this code into your game, in the VSCode debugger, your threads should look like this:

( the “No Name” thread is a normal C# thing)

STEP FIVE - The New Workflow

In order to fully utilize the power of multi-threading you must migrate away from the mindset of completing a checklist in a single block to a new pattern where systems continuously send and recieve jobs. You can think of each system as now having a mailbox that it checks periodically. This mailbox should be a concurrentQueue. (we will get to polling in a minute)

This is easier to explain with an example from my chunk manager:

The old process (step b y step)

  1. Rent a RunTimeChunk from the c hunkPool

  2. Load chunkData from disk (the main thread used to hang here waiting on the hard drive)

  3. Edit the template hex mesh

  4. Assemble and position the Ru nTimeChunk

  5. Add the RTC to the scene

The new process ( input-output)

  • OUTPUT: when the player crosses a chunk boundary the chunk manager performs the chunking process and creates a batch of lo ad3DChunk jobs

  • INPUT: When the chunk manager receives a loadedChunk it a dds it to scene

Polling

In order for my chunkManager to know it has something in the “mailBox” (a concurrentQueue called readyChunks) it has to poll it.

You could just use _Process

    public override void _Process(double delta) {
        readyChunks.TryDequeue();
	}

But this is a little overkill. This particular system will be perfectly fine with a polling rate of 10 or even 5 times a second. So I will use a timer system that performs a much more efficient poll that compares two floats. (It is still polling in _process, but comparing two floats is significantly faster than trying to dequeue)

	public override void _Process(double delta) {

		chunkingTimer += (float)delta;

		if (chunkingTimer > chunkingTick) {	
			chunkingTimer -= 1;

            readyChunks.TryDequeue();
        }

Conclusion

Thats pretty much it. I hope this guide helped you. I will add some good, visual examples at some point but for now I feel like I’ve spent too much time making this tutorial and I’m itching to get back to work on my game. I will also be making a GDScript version soon.

Not bad, not bad!

I noticed one thing though that seemed suspicious to me - the “your hard drive can only do one thing at a time” approach. I’m… not convinced. Here’s why I doubt it:

It is true, that in the olden days (and even today), hard drives - the ones with spinning silver platters inside - can indeed only read or write one thing at a time. However this limitation does not exist for SSDs. And in fact, even regular old SATA hard drives are able to internally queue up up to 32 operations. And then reorder them to get them all done faster.

For modern NVMe SSD drives the queue sizes are even (ridiculously) larger - 65K queues of 65K operations each. Which is to say - these drives will HAPPILY perform multiple operations at the same time, and, in fact, that’s how they work best. Reading one bit takes a fixed amount of time, but the more bits you can read in parallel, the faster you can get things done.

To leverage this, modern operating systems offer “Asynchronous I/O” (aka “non-blockng I/O”) capabilities - in essence, you start your read or write operations, but don’t wait for them to complete. Your read()/write() function calls return immediately with a “pending” status and some sort of “operation ID” that you can later use to check the status of the operation. This way you can issue multiple read/write requests in parallel, and the OS/drive will take care of arranging the operations in a way that makes them complete the fastest.

Note - you technically don’t even need to spin up a separate I/O thread for this. The whole “in parallel” business happens in the OS/hardware. You just periodically check whether your read operation has completed (or there might be a callback mechanism provided by the OS).

In C# this is most simply done with the -Async() versions of IO functions, although I’m not sure if this doesn’t bring in some additional nuance/pitfalls. Would need to read up on that.

Of course, this does make your code more complicated, but I think there should actually be a noticeable speedup if you try to run your reads and writes in parallel, rather than one at a time. Plus you could spare a thread…

1 Like

You got me there. I just learned something new. Thank you for pointing that out, I’ll have to remove that part when I can get back to my desktop

It’d be best to do some benchmarks first, I think, or maybe look for some data on the internet. This sort of stuff tends to be non-intuitive.

Godot doesn’t expose non-blocking I/O, it’s very platform specific so many just use threads with blocking I/O and let the OS handle scheduling.

Godot does have a WorkerThreadPool global that may help reduce your work as it does the same thing.

1 Like

This was about C# and C# does expose it.

I’d be surprised if Godot’s FileAccess differs for C#, If you are using C#'s system IO that seems like a bad idea in most cases with Godot. If there is more exposed for C# specifically could you share an example?

1 Like

Sorry, I was thinking about C#'s built-in classes (System.IO and others). Why would it be a bad idea?