Using multiple threads

    Godot supports threads and provides many handy functions to use them.

    Note

    If using other languages (C#, C++), it may be easier to use the threading classes they support.

    Warning

    Creating a thread is very simple, just use the following code:

    GDScript

    Your function will, then, run in a separate thread until it returns. Even if the function has returned already, the thread must collect it, so call Thread.wait_to_finish(), which will wait until the thread is done (if not done yet), then properly dispose of it.

    Accessing objects or data from multiple threads is not always supported (if you do it, it will cause unexpected behaviors or crashes). Read the Thread-safe APIs documentation to understand which engine APIs support multiple thread access.

    When calling , a thread ensures that all other threads will be blocked (put on suspended state) if they try to lock the same mutex. When the mutex is unlocked by calling Mutex.unlock(), the other threads will be allowed to proceed with the lock (but only one at a time).

    Here is an example of using a Mutex:

    GDScript

    Sometimes you want your thread to work “on demand”. In other words, tell it when to work and let it suspend when it isn’t doing anything. For this, Semaphores are used. The function is used in the thread to suspend it until some data arrives.

    GDScript