using_multiple_threads.rst 5.0 KB

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