A GUIDE TO MULTITHREADING (for newbs)
Multithreading is basically: Running multiple tasks at the same time. Threads are how you do this, but it isn’t the whole story.
Why it may suck when you do it!
You see, Threads are not 100% running things “at the same time”. No, you can imagine it as:
Start Task A
Pause for 2 ms
<Save
Start Task B
Pause for 2 ms
<Save
Resume Task A
This process is called context switching, and is when the CPU switches between threads.
You see, multithreading pauses, saves and resumes tasks (unless you’re on multiple cores with true parallelism). This means for simple operations (like 1 + 1 + 1), the overhead cost of saving and loading states with multithreading is actually more than if you computed it normally, making it slower.
This is why if you, for example, run a bajillion raycasts, 1 ray per 1 thread, your performance will tank. The real way to do this is to use batching and run multiple rays per thread (check out stuff like MultiRaycast for Roblox examples).
This gets you the best overall performance because: Overhead is reduced, you still compute across “parallel”.
But before you go implementing it everywhere, here is the main issue!
The Race Conditions
You see, just because the CPU pauses and loads tasks/threads does not mean race conditions are impossible, because that thread may already be modifying data, and if another thread modifies that data? Uh oh, this is bad!
Here is an analogy. Lets say you are a “video streaming” server. If someone likes a post then you simply do: (currentlikes += 1). Simple, right? But if you get 2 tasks at the same time, you’d miss one if both read the old value before writing. This is called a race condition, and happens when two tasks want to modify the same piece of data.
What many systems do is use mutexes (mutual exclusion locks) to make sure only one thread touches the data at a time, or use atomic operations that can’t be interrupted, or collect a bunch of these requests in a queue and THEN add them up in one safe thread. This is called batching updates or queuing.
“But Biblio,” you may say, hands trembling. “How do I actually multi thread in Roblox?” Well, have no fear, I am here. And I’m… Too lazy to tell you everything, because I’m writing this on my phone. Instead, here is the Roblox documentation for it. It could probably explain the method better than me anyways.
Start there, make Actors, use task.desynchronize() inside them for parallel phases, and task.synchronize() to get back to the main thread when touching instances. Just remember: Actors keep their own data isolated to avoid most race conditions automatically-- no shared mutable state unless you use SharedTable (and then be careful!).