using_multiple_threads.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. .. warning::
  12. Before using a built-in class in a thread, read :ref:`doc_thread_safe_apis`
  13. first to check whether it can be safely used in a thread.
  14. Creating a Thread
  15. -----------------
  16. To create a thread, use the following code:
  17. .. tabs::
  18. .. code-tab:: gdscript GDScript
  19. var thread: Thread
  20. # The thread will start here.
  21. func _ready():
  22. thread = Thread.new()
  23. # You can bind multiple arguments to a function Callable.
  24. thread.start(_thread_function.bind("Wafflecopter"))
  25. # Run here and exit.
  26. # The argument is the bound data passed from start().
  27. func _thread_function(userdata):
  28. # Print the userdata ("Wafflecopter")
  29. print("I'm a thread! Userdata is: ", userdata)
  30. # Thread must be disposed (or "joined"), for portability.
  31. func _exit_tree():
  32. thread.wait_to_finish()
  33. .. code-tab:: cpp C++ .H File
  34. #pragma once
  35. #include <godot_cpp/classes/node.hpp>
  36. #include <godot_cpp/classes/thread.hpp>
  37. namespace godot {
  38. class MultithreadingDemo : public Node {
  39. GDCLASS(MultithreadingDemo, Node);
  40. private:
  41. Ref<Thread> worker;
  42. protected:
  43. static void _bind_methods();
  44. void _notification(int p_what);
  45. public:
  46. MultithreadingDemo();
  47. ~MultithreadingDemo();
  48. void demo_threaded_function();
  49. };
  50. } // namespace godot
  51. .. code-tab:: cpp C++ .CPP File
  52. #include "multithreading_demo.h"
  53. #include <godot_cpp/classes/engine.hpp>
  54. #include <godot_cpp/classes/os.hpp>
  55. #include <godot_cpp/classes/time.hpp>
  56. #include <godot_cpp/core/class_db.hpp>
  57. #include <godot_cpp/variant/utility_functions.hpp>
  58. using namespace godot;
  59. void MultithreadingDemo::_bind_methods() {
  60. ClassDB::bind_method(D_METHOD("threaded_function"), &MultithreadingDemo::demo_threaded_function);
  61. }
  62. void MultithreadingDemo::_notification(int p_what) {
  63. // Prevents this from running in the editor, only during game mode. In Godot 4.3+ use Runtime classes.
  64. if (Engine::get_singleton()->is_editor_hint()) {
  65. return;
  66. }
  67. switch (p_what) {
  68. case NOTIFICATION_READY: {
  69. worker.instantiate();
  70. worker->start(callable_mp(this, &MultithreadingDemo::demo_threaded_function), Thread::PRIORITY_NORMAL);
  71. } break;
  72. case NOTIFICATION_EXIT_TREE: { // Thread must be disposed (or "joined"), for portability.
  73. // Wait until it exits.
  74. if (worker.is_valid()) {
  75. worker->wait_to_finish();
  76. }
  77. worker.unref();
  78. } break;
  79. }
  80. }
  81. MultithreadingDemo::MultithreadingDemo() {
  82. // Initialize any variables here.
  83. }
  84. MultithreadingDemo::~MultithreadingDemo() {
  85. // Add your cleanup here.
  86. }
  87. void MultithreadingDemo::demo_threaded_function() {
  88. UtilityFunctions::print("demo_threaded_function started!");
  89. int i = 0;
  90. uint64_t start = Time::get_singleton()->get_ticks_msec();
  91. while (Time::get_singleton()->get_ticks_msec() - start < 5000) {
  92. OS::get_singleton()->delay_msec(10);
  93. i++;
  94. }
  95. UtilityFunctions::print("demo_threaded_function counted to: ", i, ".");
  96. }
  97. Your function will, then, run in a separate thread until it returns.
  98. Even if the function has returned already, the thread must collect it, so call
  99. :ref:`Thread.wait_to_finish()<class_Thread_method_wait_to_finish>`, which will
  100. wait until the thread is done (if not done yet), then properly dispose of it.
  101. .. warning::
  102. Creating threads is a slow operation, especially on Windows. To avoid
  103. unnecessary performance overhead, make sure to create threads before heavy
  104. processing is needed instead of creating threads just-in-time.
  105. For example, if you need multiple threads during gameplay, you can create
  106. threads while the level is loading and only actually start processing with
  107. them later on.
  108. Additionally, locking and unlocking of mutexes can also be an expensive
  109. operation. Locking should be done carefully; avoid locking too often (or for
  110. too long).
  111. Mutexes
  112. -------
  113. Accessing objects or data from multiple threads is not always supported (if you
  114. do it, it will cause unexpected behaviors or crashes). Read the
  115. :ref:`doc_thread_safe_apis` documentation to understand which engine APIs
  116. support multiple thread access.
  117. When processing your own data or calling your own functions, as a rule, try to
  118. avoid accessing the same data directly from different threads. You may run into
  119. synchronization problems, as the data is not always updated between CPU cores
  120. when modified. Always use a :ref:`Mutex<class_Mutex>` when accessing
  121. a piece of data from different threads.
  122. When calling :ref:`Mutex.lock()<class_Mutex_method_lock>`, a thread ensures that
  123. all other threads will be blocked (put on suspended state) if they try to *lock*
  124. the same mutex. When the mutex is unlocked by calling
  125. :ref:`Mutex.unlock()<class_Mutex_method_unlock>`, the other threads will be
  126. allowed to proceed with the lock (but only one at a time).
  127. Here is an example of using a Mutex:
  128. .. tabs::
  129. .. code-tab:: gdscript GDScript
  130. var counter := 0
  131. var mutex: Mutex
  132. var thread: Thread
  133. # The thread will start here.
  134. func _ready():
  135. mutex = Mutex.new()
  136. thread = Thread.new()
  137. thread.start(_thread_function)
  138. # Increase value, protect it with Mutex.
  139. mutex.lock()
  140. counter += 1
  141. mutex.unlock()
  142. # Increment the value from the thread, too.
  143. func _thread_function():
  144. mutex.lock()
  145. counter += 1
  146. mutex.unlock()
  147. # Thread must be disposed (or "joined"), for portability.
  148. func _exit_tree():
  149. thread.wait_to_finish()
  150. print("Counter is: ", counter) # Should be 2.
  151. .. code-tab:: cpp C++ .H File
  152. #pragma once
  153. #include <godot_cpp/classes/mutex.hpp>
  154. #include <godot_cpp/classes/node.hpp>
  155. #include <godot_cpp/classes/thread.hpp>
  156. namespace godot {
  157. class MutexDemo : public Node {
  158. GDCLASS(MutexDemo, Node);
  159. private:
  160. int counter = 0;
  161. Ref<Mutex> mutex;
  162. Ref<Thread> thread;
  163. protected:
  164. static void _bind_methods();
  165. void _notification(int p_what);
  166. public:
  167. MutexDemo();
  168. ~MutexDemo();
  169. void thread_function();
  170. };
  171. } // namespace godot
  172. .. code-tab:: cpp C++ .CPP File
  173. #include "mutex_demo.h"
  174. #include <godot_cpp/classes/engine.hpp>
  175. #include <godot_cpp/classes/time.hpp>
  176. #include <godot_cpp/core/class_db.hpp>
  177. #include <godot_cpp/variant/utility_functions.hpp>
  178. using namespace godot;
  179. void MutexDemo::_bind_methods() {
  180. ClassDB::bind_method(D_METHOD("thread_function"), &MutexDemo::thread_function);
  181. }
  182. void MutexDemo::_notification(int p_what) {
  183. // Prevents this from running in the editor, only during game mode.
  184. if (Engine::get_singleton()->is_editor_hint()) {
  185. return;
  186. }
  187. switch (p_what) {
  188. case NOTIFICATION_READY: {
  189. UtilityFunctions::print("Mutex Demo Counter is starting at: ", counter);
  190. mutex.instantiate();
  191. thread.instantiate();
  192. thread->start(callable_mp(this, &MutexDemo::thread_function), Thread::PRIORITY_NORMAL);
  193. // Increase value, protect it with Mutex.
  194. mutex->lock();
  195. counter += 1;
  196. UtilityFunctions::print("Mutex Demo Counter is ", counter, " after adding with Mutex protection.");
  197. mutex->unlock();
  198. } break;
  199. case NOTIFICATION_EXIT_TREE: { // Thread must be disposed (or "joined"), for portability.
  200. // Wait until it exits.
  201. if (thread.is_valid()) {
  202. thread->wait_to_finish();
  203. }
  204. thread.unref();
  205. UtilityFunctions::print("Mutex Demo Counter is ", counter, " at EXIT_TREE."); // Should be 2.
  206. } break;
  207. }
  208. }
  209. MutexDemo::MutexDemo() {
  210. // Initialize any variables here.
  211. }
  212. MutexDemo::~MutexDemo() {
  213. // Add your cleanup here.
  214. }
  215. // Increment the value from the thread, too.
  216. void MutexDemo::thread_function() {
  217. mutex->lock();
  218. counter += 1;
  219. mutex->unlock();
  220. }
  221. Semaphores
  222. ----------
  223. Sometimes you want your thread to work *"on demand"*. In other words, tell it
  224. when to work and let it suspend when it isn't doing anything.
  225. For this, :ref:`Semaphores<class_Semaphore>` are used. The function
  226. :ref:`Semaphore.wait()<class_Semaphore_method_wait>` is used in the thread to
  227. suspend it until some data arrives.
  228. The main thread, instead, uses
  229. :ref:`Semaphore.post()<class_Semaphore_method_post>` to signal that data is
  230. ready to be processed:
  231. .. tabs::
  232. .. code-tab:: gdscript GDScript
  233. var counter := 0
  234. var mutex: Mutex
  235. var semaphore: Semaphore
  236. var thread: Thread
  237. var exit_thread := false
  238. # The thread will start here.
  239. func _ready():
  240. mutex = Mutex.new()
  241. semaphore = Semaphore.new()
  242. exit_thread = false
  243. thread = Thread.new()
  244. thread.start(_thread_function)
  245. func _thread_function():
  246. while true:
  247. semaphore.wait() # Wait until posted.
  248. mutex.lock()
  249. var should_exit = exit_thread # Protect with Mutex.
  250. mutex.unlock()
  251. if should_exit:
  252. break
  253. mutex.lock()
  254. counter += 1 # Increment counter, protect with Mutex.
  255. mutex.unlock()
  256. func increment_counter():
  257. semaphore.post() # Make the thread process.
  258. func get_counter():
  259. mutex.lock()
  260. # Copy counter, protect with Mutex.
  261. var counter_value = counter
  262. mutex.unlock()
  263. return counter_value
  264. # Thread must be disposed (or "joined"), for portability.
  265. func _exit_tree():
  266. # Set exit condition to true.
  267. mutex.lock()
  268. exit_thread = true # Protect with Mutex.
  269. mutex.unlock()
  270. # Unblock by posting.
  271. semaphore.post()
  272. # Wait until it exits.
  273. thread.wait_to_finish()
  274. # Print the counter.
  275. print("Counter is: ", counter)
  276. .. code-tab:: cpp C++ .H File
  277. #pragma once
  278. #include <godot_cpp/classes/mutex.hpp>
  279. #include <godot_cpp/classes/node.hpp>
  280. #include <godot_cpp/classes/semaphore.hpp>
  281. #include <godot_cpp/classes/thread.hpp>
  282. namespace godot {
  283. class SemaphoreDemo : public Node {
  284. GDCLASS(SemaphoreDemo, Node);
  285. private:
  286. int counter = 0;
  287. Ref<Mutex> mutex;
  288. Ref<Semaphore> semaphore;
  289. Ref<Thread> thread;
  290. bool exit_thread = false;
  291. protected:
  292. static void _bind_methods();
  293. void _notification(int p_what);
  294. public:
  295. SemaphoreDemo();
  296. ~SemaphoreDemo();
  297. void thread_function();
  298. void increment_counter();
  299. int get_counter();
  300. };
  301. } // namespace godot
  302. .. code-tab:: cpp C++ .CPP File
  303. #include "semaphore_demo.h"
  304. #include <godot_cpp/classes/engine.hpp>
  305. #include <godot_cpp/classes/time.hpp>
  306. #include <godot_cpp/core/class_db.hpp>
  307. #include <godot_cpp/variant/utility_functions.hpp>
  308. using namespace godot;
  309. void SemaphoreDemo::_bind_methods() {
  310. ClassDB::bind_method(D_METHOD("thread_function"), &SemaphoreDemo::thread_function);
  311. }
  312. void SemaphoreDemo::_notification(int p_what) {
  313. // Prevents this from running in the editor, only during game mode.
  314. if (Engine::get_singleton()->is_editor_hint()) {
  315. return;
  316. }
  317. switch (p_what) {
  318. case NOTIFICATION_READY: {
  319. UtilityFunctions::print("Semaphore Demo Counter is starting at: ", counter);
  320. mutex.instantiate();
  321. semaphore.instantiate();
  322. exit_thread = false;
  323. thread.instantiate();
  324. thread->start(callable_mp(this, &SemaphoreDemo::thread_function), Thread::PRIORITY_NORMAL);
  325. increment_counter(); // Call increment counter to test.
  326. } break;
  327. case NOTIFICATION_EXIT_TREE: { // Thread must be disposed (or "joined"), for portability.
  328. // Set exit condition to true.
  329. mutex->lock();
  330. exit_thread = true; // Protect with Mutex.
  331. mutex->unlock();
  332. // Unblock by posting.
  333. semaphore->post();
  334. // Wait until it exits.
  335. if (thread.is_valid()) {
  336. thread->wait_to_finish();
  337. }
  338. thread.unref();
  339. // Print the counter.
  340. UtilityFunctions::print("Semaphore Demo Counter is ", get_counter(), " at EXIT_TREE.");
  341. } break;
  342. }
  343. }
  344. SemaphoreDemo::SemaphoreDemo() {
  345. // Initialize any variables here.
  346. }
  347. SemaphoreDemo::~SemaphoreDemo() {
  348. // Add your cleanup here.
  349. }
  350. // Increment the value from the thread, too.
  351. void SemaphoreDemo::thread_function() {
  352. while (true) {
  353. semaphore->wait(); // Wait until posted.
  354. mutex->lock();
  355. bool should_exit = exit_thread; // Protect with Mutex.
  356. mutex->unlock();
  357. if (should_exit) {
  358. break;
  359. }
  360. mutex->lock();
  361. counter += 1; // Increment counter, protect with Mutex.
  362. mutex->unlock();
  363. }
  364. }
  365. void SemaphoreDemo::increment_counter() {
  366. semaphore->post(); // Make the thread process.
  367. }
  368. int SemaphoreDemo::get_counter() {
  369. mutex->lock();
  370. // Copy counter, protect with Mutex.
  371. int counter_value = counter;
  372. mutex->unlock();
  373. return counter_value;
  374. }