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++의 멀티스레딩 기본 형식 목록은 :ref:`doc_core_concurrency_types`를 참조하세요.
스레드
스레드를 사용하면 코드를 동시에 실행할 수 있습니다. 이는 메인 스레드에서 작업 부하를 덜어줍니다.
Godot는 스레드를 지원하고 스레드를 사용하는 데 편리한 많은 기능을 제공합니다.
참고
다른 언어(C#, C++)를 사용하는 경우 해당 언어에서 지원하는 스레딩 클래스를 사용하는 것이 더 쉬울 수 있습니다.
경고
내장 클래스를 스레드에서 사용하기 전에 먼저 :ref:`doc_thread_safe_apis`를 읽어보고 스레드에서 안전하게 사용할 수 있는지 확인하세요.
프로젝트 생성하기
인터페이스를 활성화하기 위해, 다음 코드를 실행합니다:
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, ".");
}
그러면 함수는 반환될 때까지 별도의 스레드에서 실행됩니다. 함수가 이미 반환되었더라도 스레드는 이를 수집해야 하므로 스레드가 완료될 때까지(아직 완료되지 않은 경우) 대기하는 :ref:`Thread.wait_to_finish()<class_Thread_method_wait_to_finish>`를 호출한 다음 적절하게 폐기합니다.
경고
스레드 생성은 특히 Windows에서 느린 작업입니다. 불필요한 성능 오버헤드를 방지하려면 적시에 스레드를 생성하는 대신 과도한 처리가 필요하기 전에 스레드를 생성해야 합니다.
예를 들어 게임플레이 중에 여러 스레드가 필요한 경우 레벨이 로드되는 동안 스레드를 생성하고 나중에 실제로 처리를 시작할 수 있습니다.
또한 뮤텍스를 잠그고 잠금 해제하는 것도 비용이 많이 드는 작업일 수 있습니다. 잠금은 주의해서 수행해야 합니다. 너무 자주(또는 너무 오랫동안) 잠그지 마십시오.
뮤텍스
여러 스레드에서 개체나 데이터에 액세스하는 것이 항상 지원되는 것은 아닙니다. 그렇게 하면 예기치 않은 동작이나 충돌이 발생할 수 있습니다. 다중 스레드 액세스를 지원하는 엔진 API를 이해하려면 스레드(Threads) 문서를 읽어보세요.
자신의 데이터를 처리하거나 자신의 함수를 호출할 때 원칙적으로 다른 스레드에서 동일한 데이터에 직접 액세스하지 마십시오. 수정 시 CPU 코어 간에 데이터가 항상 업데이트되지는 않으므로 동기화 문제가 발생할 수 있습니다. 다른 스레드에서 데이터 조각에 액세스할 때는 항상 :ref:`Mutex<class_Mutex>`를 사용하십시오.
:ref:`Mutex.lock()<class_Mutex_method_lock>`를 호출할 때 스레드는 다른 모든 스레드가 동일한 뮤텍스를 *잠그*려고 시도할 경우 차단(일시 중지 상태)되도록 보장합니다. :ref:`Mutex.unlock()<class_Mutex_method_unlock>`를 호출하여 뮤텍스가 잠금 해제되면 다른 스레드는 잠금을 진행할 수 있습니다(단, 한 번에 하나씩만).
어떻게 작동하는 지의 예제입니다:
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.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;
}