using_multiple_threads.rst 4.4 KB

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