2
0

using_multiple_threads.rst 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. Creating a thread is very simple, just 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. Mutexes
  40. -------
  41. Accessing objects or data from multiple threads is not always supported (if you
  42. do it, it will cause unexpected behaviors or crashes). Read the
  43. :ref:`doc_thread_safe_apis` documentation to understand which engine APIs
  44. support multiple thread access.
  45. When processing your own data or calling your own functions, as a rule, try to
  46. avoid accessing the same data directly from different threads. You may run into
  47. synchronization problems, as the data is not always updated between CPU cores
  48. when modified. Always use a :ref:`Mutex<class_Mutex>` when accessing
  49. a piece of data from different threads.
  50. When calling :ref:`Mutex.lock()<class_Mutex_method_lock>`, a thread ensures that
  51. all other threads will be blocked (put on suspended state) if they try to *lock*
  52. the same mutex. When the mutex is unlocked by calling
  53. :ref:`Mutex.unlock()<class_Mutex_method_unlock>`, the other threads will be
  54. allowed to proceed with the lock (but only one at a time).
  55. Here is an example of using a Mutex:
  56. .. tabs::
  57. .. code-tab:: gdscript GDScript
  58. var counter = 0
  59. var mutex
  60. var thread
  61. # The thread will start here.
  62. func _ready():
  63. mutex = Mutex.new()
  64. thread = Thread.new()
  65. thread.start(self, "_thread_function")
  66. # Increase value, protect it with Mutex.
  67. mutex.lock()
  68. counter += 1
  69. mutex.unlock()
  70. # Increment the value from the thread, too.
  71. func _thread_function(userdata):
  72. mutex.lock()
  73. counter += 1
  74. mutex.unlock()
  75. # Thread must be disposed (or "joined"), for portability.
  76. func _exit_tree():
  77. thread.wait_to_finish()
  78. print("Counter is: ", counter) # Should be 2.
  79. Semaphores
  80. ----------
  81. Sometimes you want your thread to work *"on demand"*. In other words, tell it
  82. when to work and let it suspend when it isn't doing anything.
  83. For this, :ref:`Semaphores<class_Semaphore>` are used. The function
  84. :ref:`Semaphore.wait()<class_Semaphore_method_wait>` is used in the thread to
  85. suspend it until some data arrives.
  86. The main thread, instead, uses
  87. :ref:`Semaphore.post()<class_Semaphore_method_post>` to signal that data is
  88. ready to be processed:
  89. .. tabs::
  90. .. code-tab:: gdscript GDScript
  91. var counter = 0
  92. var mutex
  93. var semaphore
  94. var thread
  95. var exit_thread = false
  96. # The thread will start here.
  97. func _ready():
  98. mutex = Mutex.new()
  99. semaphore = Semaphore.new()
  100. exit_thread = false
  101. thread = Thread.new()
  102. thread.start(self, "_thread_function")
  103. func _thread_function(userdata):
  104. while true:
  105. semaphore.wait() # Wait until posted.
  106. mutex.lock()
  107. var should_exit = exit_thread # Protect with Mutex.
  108. mutex.unlock()
  109. if should_exit:
  110. break
  111. mutex.lock()
  112. counter += 1 # Increment counter, protect with Mutex.
  113. mutex.unlock()
  114. func increment_counter():
  115. semaphore.post() # Make the thread process.
  116. func get_counter():
  117. mutex.lock()
  118. # Copy counter, protect with Mutex.
  119. var counter_value = counter
  120. mutex.unlock()
  121. return counter_value
  122. # Thread must be disposed (or "joined"), for portability.
  123. func _exit_tree():
  124. # Set exit condition to true.
  125. mutex.lock()
  126. exit_thread = true # Protect with Mutex.
  127. mutex.unlock()
  128. # Unblock by posting.
  129. semaphore.post()
  130. # Wait until it exits.
  131. thread.wait_to_finish()
  132. # Print the counter.
  133. print("Counter is: ", counter)