- Home /
The question is answered, right answer was accepted
Thread safe access to global array (or list) from multiple prefabs updates
Here is the situation: I got several objects of one prefab on scene, each object is trying to communicate with one global array (or list) of points in its own Update (check if it contains some point; if it is, then generate new point; if it's not, then add this point to the end of array). I got a little mess in my head about it. I know Unity is single-threaded, that should mean updates runs sorta like this (pseudo-code):
void MakeTheFrame()
{
...
object1.Update(); // access to global array
// wait for completion
object2.Update(); // access to global array
// wait for completion
object3.Update(); // access to global array
// wait for completion
...
}
And that means access to global array is consecutive and thread safe. Am I right on this point? And what about the same situation in Coroutine implementation? Where I can read more about things like that and how Unity code actually works inside?
Answer by Hilfor · Nov 01, 2015 at 11:24 PM
Yes you are right. You can find more info here http://docs.unity3d.com/Manual/ExecutionOrder.html
Right. Even coroutines run in the same thread. So at any point in time only one piece of code will execute on the main thread. Coroutines are simple "objects" which allows a coroutine scheduler to run the code in steps between yield statements. If you want to know how they work you might want to take a look at this custom coroutine scheduler implementation and this SO question