using_multiple_threads.rst 4.4 KB

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