using_multiple_threads.rst 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. .. _doc_using_multiple_threads:
  2. Using multiple threads
  3. ======================
  4. Threads
  5. -------
  6. Threads allow simultaneous execution of code. It allows off-loading work from the main thread.
  7. Godot supports threads and provides many handy functions to use them.
  8. .. note:: If using other languages (C#, C++), it may be easier to use the threading classes they support.
  9. Creating a Thread
  10. -----------------
  11. Creating a thread is very simple, just use the following code:
  12. .. tabs::
  13. .. code-tab:: gdscript GDScript
  14. var thread
  15. # The thread will start here.
  16. func _ready():
  17. thread = Thread.new()
  18. # Third argument is optional userdata, it can be any variable.
  19. thread.start(self, "_thread_function", "Wafflecopter")
  20. # Run here and exit.
  21. # The argument is the userdata passed from start().
  22. # If no argument was passed, this one still needs to
  23. # be here and it will be null.
  24. func _thread_function(userdata):
  25. # Print the userdata ("Wafflecopter")
  26. print("I'm a thread! Userdata is: ", userdata)
  27. # Thread must be disposed (or "joined"), for portability.
  28. func _exit_tree():
  29. thread.wait_to_finish()
  30. Your function will, then, run in a separate thread until it returns.
  31. Even if the function has returned already, the thread must collect it, so call
  32. :ref:`Thread.wait_to_finish()<class_Thread_method_wait_to_finish>`, which will wait until the
  33. thread is done (if not done yet), then properly dispose of it.
  34. Mutexes
  35. -------
  36. Accessing objects or data from multiple threads is not always supported (if you do it, it will
  37. cause unexpected behaviors or crashes). Read the :ref:`Thread safe APIs<doc_thread_safe_apis>`
  38. to understand which engine APIs support multiple thread access.
  39. When processing your own data or calling your own functions, as a rule, try to avoid accessing
  40. the same data directly from different threads. You may run into synchronization problems, as the
  41. data is not always updated between CPU cores when modified.
  42. Always use a :ref:`Mutex<class_Mutex>` when accessing a piece of data from different threads.
  43. When calling :ref:`Mutex.lock()<class_Mutex_method_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 us unlocked by calling :ref:`Mutex.unlock()<class_Mutex_method_unlock>`, the other threads will be allowed to proceed with the lock (but only one at a time).
  44. Here is an example of using a Mutex:
  45. .. tabs::
  46. .. code-tab:: gdscript GDScript
  47. var counter = 0
  48. var mutex
  49. var thread
  50. # The thread will start here.
  51. func _ready():
  52. mutex = Mutex.new()
  53. thread = Thread.new()
  54. thread.start(self, "_thread_function")
  55. # Increase value, protect it with Mutex.
  56. mutex.lock()
  57. counter += 1
  58. mutex.unlock()
  59. # Increment the value from the thread, too.
  60. func _thread_function(userdata):
  61. mutex.lock()
  62. counter += 1
  63. mutex.unlock()
  64. # Thread must be disposed (or "joined"), for portability.
  65. func _exit_tree():
  66. thread.wait_to_finish()
  67. print("Counter is: ", counter) # Should be 2.
  68. Semaphores
  69. ----------
  70. Sometimes you want your thread to work *"on demand"*. In other words, tell it when to work
  71. and let it suspend when it isn't doing anything.
  72. For this :ref:`Semaphores<class_Semaphore>` are used. The function :ref:`Semaphore.wait()<class_Semaphore_method_wait>`
  73. is used in the thread to suspend it until some data arrives.
  74. The main thread, instead, uses :ref:`Semaphore.post()<class_Semaphore_method_post>` to signal that data is ready to be processed:
  75. .. tabs::
  76. .. code-tab:: gdscript GDScript
  77. var counter = 0
  78. var mutex
  79. var semaphore
  80. var thread
  81. var exit_thread = false
  82. # The thread will start here.
  83. func _ready():
  84. mutex = Mutex.new()
  85. semaphore = Semaphore.new()
  86. exit_thread = false
  87. thread = Thread.new()
  88. thread.start(self, "_thread_function")
  89. func _thread_function(userdata):
  90. while true:
  91. semaphore.wait() # Wait until posted.
  92. mutex.lock()
  93. var should_exit = exit_thread # Protect with Mutex.
  94. mutex.unlock()
  95. if should_exit:
  96. break
  97. mutex.lock()
  98. counter += 1 # Increment counter, protect with Mutex.
  99. mutex.unlock()
  100. func increment_counter():
  101. semaphore.post() # Make the thread process.
  102. func get_counter():
  103. mutex.lock()
  104. # Copy counter, protect with Mutex.
  105. var counter_value = counter
  106. mutex.unlock()
  107. return counter_value
  108. # Thread must be disposed (or "joined"), for portability.
  109. func _exit_tree():
  110. # Set exit condition to true.
  111. mutex.lock()
  112. exit_thread = true # Protect with Mutex.
  113. mutex.unlock()
  114. # Unblock by posting.
  115. semaphore.post()
  116. # Wait until it exits.
  117. thread.wait_to_finish()
  118. # Print the counter.
  119. print("Counter is: ", counter)