The problem of multithreading

Video games have great multithreading potential. In theory, every GameObject can be seen as a separate entity with its own life cycle and its own computation path. This would instantaneously increase your game performance with a lot of GameObject instances. Suppose that processing all the updates in the GameObject takes 1 ms. If you could have one thousand similar GameObject instances, that would take a full second but, if you can assign each update to a separate core, all the updates could run in parallel, and your total computation time would be exactly 1 ms. That represents a 100,000% speed boost!

Unfortunately, it is not so easy. As we said before, you cannot just assign a piece of code to a core and expect that everything keeps working. A big problem with writing multithreaded code is the risk of race conditions, deadlock, and bugs that are notoriously difficult to reproduce and debug.

Race conditions are where two or more calculations are racing toward completion, but the actual outcome depends on the order in which they finish. Imagine one thread trying to add three to a number, whereas another thread multiplies it by four. The result will be different, depending on which operation happens first. Deadlock is a problem where two or more threads are competing for shared resources, where each requires the full resource collection to complete its task, but each has reserved a separate small portion of resources and refuses to relinquish control of them to another thread, in which case, none of the threads can get any work done because neither has the complete set it needs.

For this reason, traditionally, Unity APIs are not thread-safe, meaning that they cannot be invoked by different threads running in parallel. As a consequence, almost all Unity code runs in the main thread, and that includes every GameObject and MonoBehaviour (and that's why if you block a single update, you may end up freezing the entire Unity Editor).

Because multithreading is a complex topic, we will go over an example step by step.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.220.120