using_multiple_threads.rst 14 KB

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