Unity’s C# Job System

Joseph Maurer
3 min readMay 25, 2021

--

There are times when you need to take full advantage of every ounce of performance possible to make your dream game a reality. Enter the Job System in Unity. It allows the developer to write multithreaded code that can still interact with the rest of Unity.

What is multithreading?

Multithreading allows the program to run faster by taking advantage of the CPU’s ability to process many threads at the same time across multiple cores. Typically this means that a main thread spawns several other threads that in turn performs work. The problem with this is that games tend to spawn a ton of threads. So much so that the overhead causes the CPU to run less efficiently. So how do we solve this issue? You get a Job.

What is a Job?

A Job system is a group of worker threads that are being executed across multiple cores of the CPU. This allows you to save resources from having to perform context switching. The Job system operates on a Job queue where a worker thread takes an item from the queue and executes it. It does all of this while making sure to execute this in the appropriate order so that issues don’t arise. Not all Jobs have dependencies, while others do so throughput can depend on the input and dependencies associated with them. The best part? Unity’s C# Job system detects all potential race conditions and protects you from them. How sweet is that?!

Simple Jobs Example

To create a job in Unity, you need to implement the IJob interface. This interface allows you to define a struct that has parameters and an execute function. In the example below, we define a job that adds two numbers together and returns the result in an array.

Once you have the job, you need to schedule it to run in the main thread. Notice how we allocate space for the result array and then destroy it after we are done with it.

While this might seem like a very rudimentary example of Jobs, there is actually a lot you can do with them and they do provide an extreme speed benefit! Watch this video from GDC 2018 for more

Tweet me if you’ve ever used Jobs before and what you did with them!

--

--