개인 공부

코루틴(Coroutine)이란?

송현호 2023. 8. 9. 23:28

코루틴은 실행을 일시 중단하고 다시 시작하는 컴퓨터 프로그램 구성요소 중 하나로 공동 멀티태스킹을 위한 서브루틴[각주:1]을 일반화[각주:2] 한다.

 

https://en.wikipedia.org/wiki/Coroutine

 

Coroutine - Wikipedia

From Wikipedia, the free encyclopedia Computer software component Coroutines are computer program components that allow execution to be suspended and resumed, generalizing subroutines for cooperative multitasking. Coroutines are well-suited for implementin

en.wikipedia.org

 

 

 

 

 

 

 

 

코루틴을 사용하는 이유

1. 스레드[각주:3] 내에서 원하는 만큼 실행가능

(이때 스레드의 메모리 사용량이 줄어 더 많은 동시성 작업을 수행 가능하기 때문에 코루틴을 경량 스레드라고도 부른다.)

 

2. 원할 때 기능을 정지하고 다시 실행가능

 

3. 쉽게 컨텍스트를 변경 가능, 즉 한 스레드에서 다른 스레드로 쉽게 전환이 가능하다.

 

 

 

 

다음 그림과 같이 스레드를 하나의 작업장으로 생각 할 수 있고 일꾼들은 필요한 때 휴식을 취하며 필요한 곳에서 일할 수 있어야 한다. 프로그래머는 그들에게 적재적소에 맞게 명령을 내리는 상사이며, 코루틴은 이를 위한 작업 중지 명령으로 볼 수 있다.

 

https://youtu.be/ShNhJ3wMpvQ

 

 

 

 

 

 

 

 

 

 

코루틴의 예제

bool ProximityCheck()
{
    for (int i = 0; i < enemies.Length; i++)
    {
        if (Vector3.Distance(transform.position, enemies[i].transform.position) < dangerDistance) {
                return true;
        }
    }

    return false;
}
IEnumerator DoCheck()
{
    for(;;)
    {
        if (ProximityCheck())
        {
            // Perform some action here
        }
        yield return new WaitForSeconds(.1f);
    }
}
StartCoroutine(DoCheck());

다음 코드는 근처에 적이 있을 경우 플레이어에게 true를 반환하는 메서드이며 그냥 사용할 경우 메모리에 많은 과부하가 걸리지만 코루틴을 추가함으로서 시스템에 가해지는 부담을 줄일 수 있다.

 

C#의 경우 다음과 같이 IEnumerator형을 사용하며 코루틴 함수를 만나면 코드를 차례대로 실행하다가 특정 조건을 만났을 때 코루틴의 실행을 일시 중지하고 메인루틴{ex:start(), update()}으로 돌아가 특정 조건에 해당하는 코드가 끝나면 다시 코루틴으로 돌아와서 프로그램을 실행한다.

 

이때 특정 조건의 시작을 나타내는 게 yield라는 구문이며 메인루틴과의 병행성을 잘 나타내기 때문에 Coroutine이라는 이름이 붙여진 것으로 추측된다.

 

https://docs.unity3d.com/Manual/Coroutines.html

 

Unity - Manual: Coroutines

Coroutines A coroutine allows you to spread tasks across several frames. In Unity, a coroutine is a method that can pause execution and return control to Unity but then continue where it left off on the following frame. In most situations, when you call a

docs.unity3d.com

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=cdw0424&logNo=221624274241 

 

유니티(Unity) - 코루틴(Coroutine)과 yield에 대하여

코루틴을 설명하는 글은 많이 봤지만 대부분 매우 함축되어 있어서 쉽게 이해할 수 있는 글은 정말 정말 찾...

blog.naver.com

 

  1. 특정 업무를 수행하기 위해 프로그램이 호출하는 일련의 명령어 [본문으로]
  2. 특수한 개념의 공통점을 찾아 묶는 것 [본문으로]
  3. 프로세스(process) 내에서 실제로 작업을 수행하는 주체 [본문으로]