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