Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Використання кількох потоків
Дивись також
Список примітивів багатопотокової обробки в C++ див. Багатопотоковість / Паралелізм.
Потоки
Потоки дозволяють одночасне виконання коду. Це дозволяє знімати навантаження з основного потоку.
Godot підтримує потоки та надає багато зручних функцій для їх використання.
Примітка
Якщо ви використовуєте інші мови (C#, C++), можливо, буде легше використовувати класи потоків, які вони підтримують.
Попередження
Перш ніж використовувати вбудований клас у потоці, спочатку прочитайте Потокобезпечні API, щоб перевірити, чи можна безпечно використовувати його в потоці.
Створення потоку
Щоб створити потік, використовуйте наступний код:
var thread: Thread
# The thread will start here.
func _ready():
thread = Thread.new()
# You can bind multiple arguments to a function Callable.
thread.start(_thread_function.bind("Wafflecopter"))
# Run here and exit.
# The argument is the bound data passed from start().
func _thread_function(userdata):
# Print the userdata ("Wafflecopter")
print("I'm a thread! Userdata is: ", userdata)
# Thread must be disposed (or "joined"), for portability.
func _exit_tree():
thread.wait_to_finish()
#pragma once
#include <godot_cpp/classes/node.hpp>
#include <godot_cpp/classes/thread.hpp>
namespace godot {
class MultithreadingDemo : public Node {
GDCLASS(MultithreadingDemo, Node);
private:
Ref<Thread> worker;
protected:
static void _bind_methods();
void _notification(int p_what);
public:
MultithreadingDemo();
~MultithreadingDemo();
void demo_threaded_function();
};
} // namespace godot
#include "multithreading_demo.h"
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/os.hpp>
#include <godot_cpp/classes/time.hpp>
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
using namespace godot;
void MultithreadingDemo::_bind_methods() {
ClassDB::bind_method(D_METHOD("threaded_function"), &MultithreadingDemo::demo_threaded_function);
}
void MultithreadingDemo::_notification(int p_what) {
// Prevents this from running in the editor, only during game mode. In Godot 4.3+ use Runtime classes.
if (Engine::get_singleton()->is_editor_hint()) {
return;
}
switch (p_what) {
case NOTIFICATION_READY: {
worker.instantiate();
worker->start(callable_mp(this, &MultithreadingDemo::demo_threaded_function), Thread::PRIORITY_NORMAL);
} break;
case NOTIFICATION_EXIT_TREE: { // Thread must be disposed (or "joined"), for portability.
// Wait until it exits.
if (worker.is_valid()) {
worker->wait_to_finish();
}
worker.unref();
} break;
}
}
MultithreadingDemo::MultithreadingDemo() {
// Initialize any variables here.
}
MultithreadingDemo::~MultithreadingDemo() {
// Add your cleanup here.
}
void MultithreadingDemo::demo_threaded_function() {
UtilityFunctions::print("demo_threaded_function started!");
int i = 0;
uint64_t start = Time::get_singleton()->get_ticks_msec();
while (Time::get_singleton()->get_ticks_msec() - start < 5000) {
OS::get_singleton()->delay_msec(10);
i++;
}
UtilityFunctions::print("demo_threaded_function counted to: ", i, ".");
}
Тоді ваша функція виконуватиметься в окремому потоці, доки не повернеться. Навіть якщо функція вже повернулася, потік має її зібрати, тому викличте Thread.wait_to_finish(), яка чекатиме, поки потік завершиться (якщо ще не завершено), а потім належним чином утилізує його.
Попередження
Створення потоків є повільною операцією, особливо в Windows. Щоб уникнути непотрібних витрат на продуктивність, створюйте потоки до того, як знадобиться важка обробка, замість того, щоб створювати потоки вчасно.
Наприклад, якщо вам потрібно кілька потоків під час гри, ви можете створити потоки під час завантаження рівня й фактично розпочати їх обробку пізніше.
Крім того, блокування та розблокування м'ютексів також може бути дорогою операцією. Замикання слід проводити акуратно; уникайте занадто частого (або надто тривалого) блокування.
Мьютекси
Доступ до об’єктів або даних із кількох потоків не завжди підтримується (якщо ви це зробите, це призведе до неочікуваної поведінки або збоїв). Прочитайте документацію Потокобезпечні API, щоб зрозуміти, які API механізму підтримують багатопотоковий доступ.
Під час обробки власних даних або виклику власних функцій, як правило, намагайтеся уникати доступу до тих самих даних безпосередньо з різних потоків. Ви можете зіткнутися з проблемами синхронізації, оскільки дані не завжди оновлюються між ядрами ЦП у разі їх зміни. Завжди використовуйте Mutex під час доступу до частини даних з різних потоків.
Під час виклику Mutex.lock() потік гарантує, що всі інші потоки будуть заблоковані (переведені в стан призупинення), якщо вони спробують заблокувати той самий м’ютекс. Коли м’ютекс розблоковано викликом Mutex.unlock(), іншим потокам буде дозволено продовжити блокування (але лише по одному).
Ось приклад використання Mutex:
var counter := 0
var mutex: Mutex
var thread: Thread
# The thread will start here.
func _ready():
mutex = Mutex.new()
thread = Thread.new()
thread.start(_thread_function)
# Increase value, protect it with Mutex.
mutex.lock()
counter += 1
mutex.unlock()
# Increment the value from the thread, too.
func _thread_function():
mutex.lock()
counter += 1
mutex.unlock()
# Thread must be disposed (or "joined"), for portability.
func _exit_tree():
thread.wait_to_finish()
print("Counter is: ", counter) # Should be 2.
#pragma once
#include <godot_cpp/classes/mutex.hpp>
#include <godot_cpp/classes/node.hpp>
#include <godot_cpp/classes/thread.hpp>
namespace godot {
class MutexDemo : public Node {
GDCLASS(MutexDemo, Node);
private:
int counter = 0;
Ref<Mutex> mutex;
Ref<Thread> thread;
protected:
static void _bind_methods();
void _notification(int p_what);
public:
MutexDemo();
~MutexDemo();
void thread_function();
};
} // namespace godot
#include "mutex_demo.h"
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/time.hpp>
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
using namespace godot;
void MutexDemo::_bind_methods() {
ClassDB::bind_method(D_METHOD("thread_function"), &MutexDemo::thread_function);
}
void MutexDemo::_notification(int p_what) {
// Prevents this from running in the editor, only during game mode.
if (Engine::get_singleton()->is_editor_hint()) {
return;
}
switch (p_what) {
case NOTIFICATION_READY: {
UtilityFunctions::print("Mutex Demo Counter is starting at: ", counter);
mutex.instantiate();
thread.instantiate();
thread->start(callable_mp(this, &MutexDemo::thread_function), Thread::PRIORITY_NORMAL);
// Increase value, protect it with Mutex.
mutex->lock();
counter += 1;
UtilityFunctions::print("Mutex Demo Counter is ", counter, " after adding with Mutex protection.");
mutex->unlock();
} break;
case NOTIFICATION_EXIT_TREE: { // Thread must be disposed (or "joined"), for portability.
// Wait until it exits.
if (thread.is_valid()) {
thread->wait_to_finish();
}
thread.unref();
UtilityFunctions::print("Mutex Demo Counter is ", counter, " at EXIT_TREE."); // Should be 2.
} break;
}
}
MutexDemo::MutexDemo() {
// Initialize any variables here.
}
MutexDemo::~MutexDemo() {
// Add your cleanup here.
}
// Increment the value from the thread, too.
void MutexDemo::thread_function() {
mutex->lock();
counter += 1;
mutex->unlock();
}
Семафори
Іноді ви хочете, щоб ваш потік працював "на вимогу". Іншими словами, скажіть йому, коли працювати, і дозвольте йому призупинити, коли він нічого не робить. Для цього використовуються Semaphores. Функція Semaphore.wait() використовується в потоці, щоб призупинити його до отримання певних даних.
Натомість основний потік використовує Semaphore.post(), щоб повідомити, що дані готові до обробки:
var counter := 0
var mutex: Mutex
var semaphore: Semaphore
var thread: Thread
var exit_thread := false
# The thread will start here.
func _ready():
mutex = Mutex.new()
semaphore = Semaphore.new()
exit_thread = false
thread = Thread.new()
thread.start(_thread_function)
func _thread_function():
while true:
semaphore.wait() # Wait until posted.
mutex.lock()
var should_exit = exit_thread # Protect with Mutex.
mutex.unlock()
if should_exit:
break
mutex.lock()
counter += 1 # Increment counter, protect with Mutex.
mutex.unlock()
func increment_counter():
semaphore.post() # Make the thread process.
func get_counter():
mutex.lock()
# Copy counter, protect with Mutex.
var counter_value = counter
mutex.unlock()
return counter_value
# Thread must be disposed (or "joined"), for portability.
func _exit_tree():
# Set exit condition to true.
mutex.lock()
exit_thread = true # Protect with Mutex.
mutex.unlock()
# Unblock by posting.
semaphore.post()
# Wait until it exits.
thread.wait_to_finish()
# Print the counter.
print("Counter is: ", counter)
#pragma once
#include <godot_cpp/classes/mutex.hpp>
#include <godot_cpp/classes/node.hpp>
#include <godot_cpp/classes/semaphore.hpp>
#include <godot_cpp/classes/thread.hpp>
namespace godot {
class SemaphoreDemo : public Node {
GDCLASS(SemaphoreDemo, Node);
private:
int counter = 0;
Ref<Mutex> mutex;
Ref<Semaphore> semaphore;
Ref<Thread> thread;
bool exit_thread = false;
protected:
static void _bind_methods();
void _notification(int p_what);
public:
SemaphoreDemo();
~SemaphoreDemo();
void thread_function();
void increment_counter();
int get_counter();
};
} // namespace godot
#include "semaphore_demo.h"
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/time.hpp>
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
using namespace godot;
void SemaphoreDemo::_bind_methods() {
ClassDB::bind_method(D_METHOD("thread_function"), &SemaphoreDemo::thread_function);
}
void SemaphoreDemo::_notification(int p_what) {
// Prevents this from running in the editor, only during game mode.
if (Engine::get_singleton()->is_editor_hint()) {
return;
}
switch (p_what) {
case NOTIFICATION_READY: {
UtilityFunctions::print("Semaphore Demo Counter is starting at: ", counter);
mutex.instantiate();
semaphore.instantiate();
exit_thread = false;
thread.instantiate();
thread->start(callable_mp(this, &SemaphoreDemo::thread_function), Thread::PRIORITY_NORMAL);
increment_counter(); // Call increment counter to test.
} break;
case NOTIFICATION_EXIT_TREE: { // Thread must be disposed (or "joined"), for portability.
// Set exit condition to true.
mutex->lock();
exit_thread = true; // Protect with Mutex.
mutex->unlock();
// Unblock by posting.
semaphore->post();
// Wait until it exits.
if (thread.is_valid()) {
thread->wait_to_finish();
}
thread.unref();
// Print the counter.
UtilityFunctions::print("Semaphore Demo Counter is ", get_counter(), " at EXIT_TREE.");
} break;
}
}
SemaphoreDemo::SemaphoreDemo() {
// Initialize any variables here.
}
SemaphoreDemo::~SemaphoreDemo() {
// Add your cleanup here.
}
// Increment the value from the thread, too.
void SemaphoreDemo::thread_function() {
while (true) {
semaphore->wait(); // Wait until posted.
mutex->lock();
bool should_exit = exit_thread; // Protect with Mutex.
mutex->unlock();
if (should_exit) {
break;
}
mutex->lock();
counter += 1; // Increment counter, protect with Mutex.
mutex->unlock();
}
}
void SemaphoreDemo::increment_counter() {
semaphore->post(); // Make the thread process.
}
int SemaphoreDemo::get_counter() {
mutex->lock();
// Copy counter, protect with Mutex.
int counter_value = counter;
mutex->unlock();
return counter_value;
}