Using multiple threads

Threads

Threads allow simultaneous execution of code. It allows off-loading work from the main thread.

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.

Creating a Thread

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

GDScript

  1. var thread
  2. # The thread will start here.
  3. func _ready():
  4. thread = Thread.new()
  5. # Third argument is optional userdata, it can be any variable.
  6. thread.start(self, "_thread_function", "Wafflecopter")
  7. # Run here and exit.
  8. # The argument is the userdata passed from start().
  9. # If no argument was passed, this one still needs to
  10. # be here and it will be null.
  11. func _thread_function(userdata):
  12. # Print the userdata ("Wafflecopter")
  13. print("I'm a thread! Userdata is: ", userdata)
  14. # Thread must be disposed (or "joined"), for portability.
  15. func _exit_tree():
  16. thread.wait_to_finish()

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.

Mutexes

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 to understand which engine APIs support multiple thread access.

When processing your own data or calling your own functions, as a rule, try to avoid accessing the same data directly from different threads. You may run into synchronization problems, as the data is not always updated between CPU cores when modified. Always use a Mutex when accessing a piece of data from different threads.

When calling Mutex.lock(), 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

  1. var counter = 0
  2. var mutex
  3. var thread
  4. # The thread will start here.
  5. func _ready():
  6. mutex = Mutex.new()
  7. thread = Thread.new()
  8. thread.start(self, "_thread_function")
  9. # Increase value, protect it with Mutex.
  10. mutex.lock()
  11. counter += 1
  12. mutex.unlock()
  13. # Increment the value from the thread, too.
  14. func _thread_function(userdata):
  15. mutex.lock()
  16. counter += 1
  17. mutex.unlock()
  18. # Thread must be disposed (or "joined"), for portability.
  19. func _exit_tree():
  20. thread.wait_to_finish()
  21. print("Counter is: ", counter) # Should be 2.

Semaphores

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 Semaphore.wait() is used in the thread to suspend it until some data arrives.

The main thread, instead, uses Semaphore.post() to signal that data is ready to be processed:

GDScript

  1. var counter = 0
  2. var mutex
  3. var semaphore
  4. var thread
  5. var exit_thread = false
  6. # The thread will start here.
  7. func _ready():
  8. mutex = Mutex.new()
  9. semaphore = Semaphore.new()
  10. exit_thread = false
  11. thread = Thread.new()
  12. thread.start(self, "_thread_function")
  13. func _thread_function(userdata):
  14. while true:
  15. semaphore.wait() # Wait until posted.
  16. mutex.lock()
  17. var should_exit = exit_thread # Protect with Mutex.
  18. mutex.unlock()
  19. if should_exit:
  20. break
  21. mutex.lock()
  22. counter += 1 # Increment counter, protect with Mutex.
  23. mutex.unlock()
  24. func increment_counter():
  25. semaphore.post() # Make the thread process.
  26. func get_counter():
  27. mutex.lock()
  28. # Copy counter, protect with Mutex.
  29. var counter_value = counter
  30. mutex.unlock()
  31. return counter_value
  32. # Thread must be disposed (or "joined"), for portability.
  33. func _exit_tree():
  34. # Set exit condition to true.
  35. mutex.lock()
  36. exit_thread = true # Protect with Mutex.
  37. mutex.unlock()
  38. # Unblock by posting.
  39. semaphore.post()
  40. # Wait until it exits.
  41. thread.wait_to_finish()
  42. # Print the counter.
  43. print("Counter is: ", counter)