using_multiple_threads.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 at runtime is slow on Windows and should be avoided to
  105. prevent stuttering. Semaphores, explained later on this page, should be used
  106. instead.
  107. Mutexes
  108. -------
  109. Accessing objects or data from multiple threads is not always supported (if you
  110. do it, it will cause unexpected behaviors or crashes). Read the
  111. :ref:`doc_thread_safe_apis` documentation to understand which engine APIs
  112. support multiple thread access.
  113. When processing your own data or calling your own functions, as a rule, try to
  114. avoid accessing the same data directly from different threads. You may run into
  115. synchronization problems, as the data is not always updated between CPU cores
  116. when modified. Always use a :ref:`Mutex<class_Mutex>` when accessing
  117. a piece of data from different threads.
  118. When calling :ref:`Mutex.lock()<class_Mutex_method_lock>`, a thread ensures that
  119. all other threads will be blocked (put on suspended state) if they try to *lock*
  120. the same mutex. When the mutex is unlocked by calling
  121. :ref:`Mutex.unlock()<class_Mutex_method_unlock>`, the other threads will be
  122. allowed to proceed with the lock (but only one at a time).
  123. Here is an example of using a Mutex:
  124. .. tabs::
  125. .. code-tab:: gdscript GDScript
  126. var counter := 0
  127. var mutex: Mutex
  128. var thread: Thread
  129. # The thread will start here.
  130. func _ready():
  131. mutex = Mutex.new()
  132. thread = Thread.new()
  133. thread.start(_thread_function)
  134. # Increase value, protect it with Mutex.
  135. mutex.lock()
  136. counter += 1
  137. mutex.unlock()
  138. # Increment the value from the thread, too.
  139. func _thread_function():
  140. mutex.lock()
  141. counter += 1
  142. mutex.unlock()
  143. # Thread must be disposed (or "joined"), for portability.
  144. func _exit_tree():
  145. thread.wait_to_finish()
  146. print("Counter is: ", counter) # Should be 2.
  147. .. code-tab:: cpp C++ .H File
  148. #ifndef MUTEX_DEMO_H
  149. #define MUTEX_DEMO_H
  150. #include <godot_cpp/classes/mutex.hpp>
  151. #include <godot_cpp/classes/node.hpp>
  152. #include <godot_cpp/classes/thread.hpp>
  153. namespace godot {
  154. class MutexDemo : public Node {
  155. GDCLASS(MutexDemo, Node);
  156. private:
  157. int counter = 0;
  158. Ref<Mutex> mutex;
  159. Ref<Thread> thread;
  160. protected:
  161. static void _bind_methods();
  162. void _notification(int p_what);
  163. public:
  164. MutexDemo();
  165. ~MutexDemo();
  166. void thread_function();
  167. };
  168. } // namespace godot
  169. #endif // MUTEX_DEMO_H
  170. .. code-tab:: cpp C++ .CPP File
  171. #include "mutex_demo.h"
  172. #include <godot_cpp/classes/engine.hpp>
  173. #include <godot_cpp/classes/time.hpp>
  174. #include <godot_cpp/core/class_db.hpp>
  175. #include <godot_cpp/variant/utility_functions.hpp>
  176. using namespace godot;
  177. void MutexDemo::_bind_methods() {
  178. ClassDB::bind_method(D_METHOD("thread_function"), &MutexDemo::thread_function);
  179. }
  180. void MutexDemo::_notification(int p_what) {
  181. // Prevents this from running in the editor, only during game mode.
  182. if (Engine::get_singleton()->is_editor_hint()) {
  183. return;
  184. }
  185. switch (p_what) {
  186. case NOTIFICATION_READY: {
  187. UtilityFunctions::print("Mutex Demo Counter is starting at: ", counter);
  188. mutex.instantiate();
  189. thread.instantiate();
  190. thread->start(callable_mp(this, &MutexDemo::thread_function), Thread::PRIORITY_NORMAL);
  191. // Increase value, protect it with Mutex.
  192. mutex->lock();
  193. counter += 1;
  194. UtilityFunctions::print("Mutex Demo Counter is ", counter, " after adding with Mutex protection.");
  195. mutex->unlock();
  196. } break;
  197. case NOTIFICATION_EXIT_TREE: { // Thread must be disposed (or "joined"), for portability.
  198. // Wait until it exits.
  199. if (thread.is_valid()) {
  200. thread->wait_to_finish();
  201. }
  202. thread.unref();
  203. UtilityFunctions::print("Mutex Demo Counter is ", counter, " at EXIT_TREE."); // Should be 2.
  204. } break;
  205. }
  206. }
  207. MutexDemo::MutexDemo() {
  208. // Initialize any variables here.
  209. }
  210. MutexDemo::~MutexDemo() {
  211. // Add your cleanup here.
  212. }
  213. // Increment the value from the thread, too.
  214. void MutexDemo::thread_function() {
  215. mutex->lock();
  216. counter += 1;
  217. mutex->unlock();
  218. }
  219. Semaphores
  220. ----------
  221. Sometimes you want your thread to work *"on demand"*. In other words, tell it
  222. when to work and let it suspend when it isn't doing anything.
  223. For this, :ref:`Semaphores<class_Semaphore>` are used. The function
  224. :ref:`Semaphore.wait()<class_Semaphore_method_wait>` is used in the thread to
  225. suspend it until some data arrives.
  226. The main thread, instead, uses
  227. :ref:`Semaphore.post()<class_Semaphore_method_post>` to signal that data is
  228. ready to be processed:
  229. .. tabs::
  230. .. code-tab:: gdscript GDScript
  231. var counter := 0
  232. var mutex: Mutex
  233. var semaphore: Semaphore
  234. var thread: Thread
  235. var exit_thread := false
  236. # The thread will start here.
  237. func _ready():
  238. mutex = Mutex.new()
  239. semaphore = Semaphore.new()
  240. exit_thread = false
  241. thread = Thread.new()
  242. thread.start(_thread_function)
  243. func _thread_function():
  244. while true:
  245. semaphore.wait() # Wait until posted.
  246. mutex.lock()
  247. var should_exit = exit_thread # Protect with Mutex.
  248. mutex.unlock()
  249. if should_exit:
  250. break
  251. mutex.lock()
  252. counter += 1 # Increment counter, protect with Mutex.
  253. mutex.unlock()
  254. func increment_counter():
  255. semaphore.post() # Make the thread process.
  256. func get_counter():
  257. mutex.lock()
  258. # Copy counter, protect with Mutex.
  259. var counter_value = counter
  260. mutex.unlock()
  261. return counter_value
  262. # Thread must be disposed (or "joined"), for portability.
  263. func _exit_tree():
  264. # Set exit condition to true.
  265. mutex.lock()
  266. exit_thread = true # Protect with Mutex.
  267. mutex.unlock()
  268. # Unblock by posting.
  269. semaphore.post()
  270. # Wait until it exits.
  271. thread.wait_to_finish()
  272. # Print the counter.
  273. print("Counter is: ", counter)
  274. .. code-tab:: cpp C++ .H File
  275. #ifndef SEMAPHORE_DEMO_H
  276. #define SEMAPHORE_DEMO_H
  277. #include <godot_cpp/classes/mutex.hpp>
  278. #include <godot_cpp/classes/node.hpp>
  279. #include <godot_cpp/classes/semaphore.hpp>
  280. #include <godot_cpp/classes/thread.hpp>
  281. namespace godot {
  282. class SemaphoreDemo : public Node {
  283. GDCLASS(SemaphoreDemo, Node);
  284. private:
  285. int counter = 0;
  286. Ref<Mutex> mutex;
  287. Ref<Semaphore> semaphore;
  288. Ref<Thread> thread;
  289. bool exit_thread = false;
  290. protected:
  291. static void _bind_methods();
  292. void _notification(int p_what);
  293. public:
  294. SemaphoreDemo();
  295. ~SemaphoreDemo();
  296. void thread_function();
  297. void increment_counter();
  298. int get_counter();
  299. };
  300. } // namespace godot
  301. #endif // SEMAPHORE_DEMO_H
  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. }