using_multiple_threads.rst 5.3 KB

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