- Home /
Coroutine... should I worry about synchronization or not?
Currently I'm handling my game control as part of the OnTriggerEnter2D event, everything works fine, however the game looks slow at times, so in order to optimize performance I want to move such code to a co-routine, however I still will be creating, updating and destroying objects inside OnTriggerEnter2D as it is the natural place to do so...
I don't have enough knowledge or experience in Unity, so I have a big doubt here: should I worry about synchronization or not??? If the co-routine is called from the same thread as the OnTriggerEnter2D event, then I don't even need to worry about synchronization, however if different threads are involved I better provide a synchronization method otherwise things can go really really wrong.
Anyone with experience in co-routines can provide some light please?
Answer by Bunny83 · Jun 18, 2014 at 03:27 PM
Coroutines run in the main thread, like most parts of scripting environment. So you don't have to worry about synchronization. The only things which might run in parallel are internal background things you usually don't have access to.
Thanks, I do appreciate your answer. After several tests, it seem your statements are absolutely right, but just to be 100% sure, is there any official documentation I can refer to???.
Thanks, I read both articles previously, but in none of them it is clearly stated that Coroutines run on the main thread, that's precisely the reason for my doubts, and that's why I posted this question.
Coroutines are actually objects and not routines in the traditional sense. The "coroutine objects" implement cooperative multitasking, so they never run simultaneously with their calling code. The whole scripting environment of Unity runs on a single thread, that's why they don't care to make any API thread-safe. As I said, only a few internal processes might run on a seperate thread (on the native C++ side) but the whole managed world runs in the main thread.
There are a few exceptions now, like the new serialization callbacks which might be called from the loading thread as well as object constructors which you shouldn't use mainly for that reason.
However the coroutine scheduler definitely runs on the main thread. There are actually just a few points in the mainloop where the scheduler "schedules" a coroutine. Even asynchronous tasks like a WWW request are scheduled on the main thread so you never have to worry about threading.
You might want to read the coroutines++ and advanced coroutines articles on UnityGems to get a better understanding of how coroutines are implemented in Unity.
Thanks, these two articles are really worth reading. I Appreciate it very much