During my early days as a backend developer, I built my first parallel feature. It was a small algorithm that ran on multiple threads to generate data that would go into a report. At the time, I lacked experience with parallelism and concurrency, and I didn’t fully understand what I was doing. It was way before concurrency and cloud computing became a thing. Despite all that, the application worked amazingly.
Years went by, and I got a lot more experience using parallel computing in both backend development and gaming development. Now I could understand the concepts, challenges, and practical applications behind these techniques. In this article, I want to share the lessons from my experience. I also want to help others who might be going through the same journey. So I decided to compare some techniques that work in both backend and game development. For that, I use examples from my own experience. They show where each technique works, its common pitfalls, and solutions that can mitigate them.
They are starving!
Let’s imagine we are in a restaurant. The waiter should not take more than one minute to run all the tables and take orders. If there are few customers at the tables, the waiter has a good amount of time to listen to the current customer. Then he moves to the next table and eventually takes the order of all customers in one minute, for example. As time passes, more customers arrive, so the waiter has less and less time to listen to each request. This forces him to make more rounds around the room to attend to all customers.
That’s what thread starvation looks like! Your CPU does not run everything at the same time; instead, it runs parts of the code in a time slice. If you have many processes to execute, they’ll process fewer instructions because the slices of time will be smaller!
Race conditions
Race conditions are the second worst problem on concurrency, right behind the race conditions! Data corruption, system locks, and syncing are the main issues here. These problems happen when two or more processes try to manipulate the same resources at the same time! They are unpredictable, which makes them hard to debug. Also, there is no silver bullet solution for this problem. To make it worse, the solutions might come with severe drawbacks!
Concurrency
Concurrency happens when you have two or more processes sharing the same resources. Whether the processes relate or not, at some point you know you need to sync everything together. Data corruption, locks, sync latency, and race conditions are the most challenging issues in concurrency. The synchronization may cause unexpected delays that may be worse than non-concurrent processes. Also, badly defined critical sections or misuse of locking techniques may cause the applications to freeze.
Backend development relies on thread pools and message queues, two well-known techniques, to mitigate the concurrency issues. However, in game development, it’s common to work at a much lower level, where these techniques aren’t always applicable.
Immutability
The cool kids on functional programming are already familiar with this. As the name suggests, it’s just about not changing the values you use during the process. If you need to change some value, create a copy of that variable and then change it!
It can prevent data corruption, since the data never changes and no lock or sync is necessary. One good use case is when multiple AI threads operate on the same target. If the target does not change until the end of the processes, any AI thread can safely query it. That means no fear of data corruption and no need for any kind of lock. However, you have to ensure there is no change on target until all the AI threads have finished their operations.
Critical sections
You can define critical sections with locking techniques (like mutexes, spin locks, semaphores, etc.). They help to prevent data corruption and synchronize the variables that different threads use. But if you implement them poorly, they can drastically reduce game performance. In the worst cases, they can make the game freeze at random moments.
A mutex can prevent a thread from writing to a variable while another one reads it. Semaphores may block different sections of the code without completely stopping execution. Spin locks, in turn, may prevent processes from staying locked, waiting on each other.
For example, consider a physics thread running. There is no need for locks while it executes non-critical operations. But the moment the thread must write the results for the other threads to read, a critical section occurs. This critical section ensures that the physics thread does not write while another thread is reading. Alternatively, it makes the reading thread wait until the physics thread finishes writing.
Actor models
Actor models operate at a higher level. They consist of entities with self-centered states that use communication channels to trade information between themselves. This approach is beneficial in game development since it stops entities from sharing mutable states. That ensures that no data corruption will happen.
This strategy is excellent for a large number of entities. A good use case is in crowd manager systems. There, you can create crowd manager actors that could run independently and control the crowd members, which also run independently. With communication channels passing information between them, this setup can make the system flexible. It becomes flexible enough to integrate the crowd manager with AI systems. The crowd manager can then delegate this communication with AI APIs without compromising the crowd member itself.
Parallelism
Parallelism is at the opposite end of the spectrum from concurrency: two or more processes run without sharing resources. At first, they seem to be safe, but we need to pay attention to various points. Synchronization overheads and thread starvation are the most common problems here. It is important to plan ahead how to start the execution and how to collect these results, if applicable. As I mentioned before, I’ll present a few issues and techniques along with some use cases.
Fire and forget
When you need to execute a process and can ignore its result, fire-and-forget is a good strategy. If unmanaged, fired-and-forgotten tasks risk hanging and never terminating, and they may cause thread starvation. That’s why I advise using a manager, a thread pool system, or an observer to avoid this issue.
On the backend, this technique suits logging, generating reports, condensing data, and any process whose result you don’t need directly. In games, you can use Fire-and-Forget for non-vital visual effects or achievement registering. It also fits any other process where you expect a side effect but don’t need the result of the operation.
Worker queue
A worker queue is a technique where you create the data that the tasks need to run and then store it in a queue. At a given moment, a worker will pull that data and use it to run a thread. This strategy has many advantages. For example, it lets you control how many workers can process the queue. It also avoids starvation, since it limits resource usage based on the workers. You can also define how many machine resources a worker can use.
Many small workers can process many small tasks quickly, while a few heavy workers can handle more demanding tasks. Either way, the program makes more efficient use of the machine resources. You can use worker queues for asynchronous loading or preparatory tasks for other processes (like rendering or physics).