using_multiple_threads.rst 5.3 KB

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