using_multiple_threads.rst 4.6 KB

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