using_multiple_threads.rst 5.0 KB

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