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.

멀티스레드 사용하기

더 보기

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()

그러면 함수는 반환될 때까지 별도의 스레드에서 실행됩니다. 함수가 이미 반환되었더라도 스레드는 이를 수집해야 하므로 스레드가 완료될 때까지(아직 완료되지 않은 경우) 대기하는 :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.

세마포어

때로는 스레드가 "요청 시" 작동하기를 원할 수도 있습니다. 즉, 작업할 시기를 알려주고 아무것도 하지 않을 때는 일시 중지되도록 합니다. 이를 위해 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)