Skip to content

Threadsafe Collections Script

Erik edited this page Nov 11, 2019 · 2 revisions

I have some super complex code that takes a few seconds to run.

What would you do:

A. Deal with it. The player is patient.

B. Make it into a coroutine.

C. Multithread.

D. Never finish the project because you get burnt out trying to solve issues that aren't gamebreaking, but you don't want to release an unfinished product.

If you picked B or C, you're on the right track!

Now try to separate parts of your code into 2 categories: Data-based, and Engine-based.

If a part of your codes moves a transform, instantiates an object, reads from a texture, or modifies game components, that's engine-based. (yellow highlight the code that is engine based)

If a part of your code is working with data, that's data-based. (soft blue highlight the code that involves data).

It's likely that there is some code that does both. Let's create temporary variables to separate the data logic from the engine logic. Something important to note: since we will be working with threads, we run the risk of thread contention if we use non-primitives. Consider using threadsafe datatypes to communicate between threads.

Great! We now have a chunk of code that performs data-based logic. Let's move that to a thread.

In order to prevent runaway threads from happening, let's abort this thread in the event that my monobehavior is destroyed. That way, if the game is closed our thread stops running.

Now let's extract the data-based logic from our monobehaviour and put it into a method on our thread. The class is given a constructor to set its properties, and the thread is exposed via a "Run" method.

Threads can't access eachother, but a non-primitive threadsafe collection can be used to pass data.

The original complex code can now be replaced with a constructor for the thread, and move the later logic to a coroutine that will run once the thread is completed.

Alternatively, since a threadsafe collection is being used to pass data, the thread does not have to be completed before processing. Show periodic number generation.

Use cases:

  • Procedural dungeon generation
  • Complex mathematics
  • Image processing
  • Working with large arrays

Show how to do the same thing in Unity's Jobs system

Clone this wiki locally