등등

코루틴(Coroutine)

땍땍 2025. 8. 17. 12:40

📕 코루틴(Coroutine)

코루틴은 비동기 프로그래밍과 동시성(concurrency) 처리를 지원하는 프로그래밍 구조로,

함수 실행을 일시 중단(suspend) 했다가 필요할 때 재개(resume) 할 수 있다.

 


🔍  스레드(Thread) vs 코루틴(Coroutine)

구분 스레드(Thread) 코루틴(Coroutine)

관계 OS가 관리하는 실행 단위 스레드 위에서 동작하는 더 작은 실행 단위
생성/관리 비용 무겁고 비용이 큼 (스택, OS 자원 필요) 가볍고 저렴 (메모리 오버헤드 적음)
Context Switching 커널 모드 전환이 필요해 오버헤드 발생 Continuation 객체로 관리, 오버헤드 최소화
병행성/병렬성 CPU 코어 수에 따라 실제 병렬 실행 가능 단일 스레드에서도 병행 실행 가능 (협력적 실행)
제어 방식 OS 스케줄러에 의해 강제로 스위칭 개발자가 명시적으로 suspend / resume 제어

 


🔍 Continuation

Continuation은 코루틴의 중단과 재개를 관리하는 객체이다.

  • 코루틴이 중단될 때: 변수 값, 실행 위치 등 당시의 실행 환경을 저장한다.
  • 코루틴이 재개될 때: 저장된 정보를 이용해 중단된 지점부터 다시 실행할 수 있도록 한다.
package kotlin.coroutines

import kotlin.contracts.*
import kotlin.coroutines.intrinsics.*
import kotlin.internal.InlineOnly

@SinceKotlin("1.3")
public interface Continuation<in T> {
    /**
     * The context of the coroutine that corresponds to this continuation.
     */
    public val context: CoroutineContext

    /**
     * Resumes the execution of the corresponding coroutine passing a successful or failed [result] as the
     * return value of the last suspension point.
     */
    public fun resumeWith(result: Result<T>)
}

 

 


🔍 Continuation Builder

빌더 / 함수 설명 반환값 특징

runBlocking 코루틴이 완료될 때까지 현재 스레드를 블로킹 X 일반 코드에서 코루틴을 동기적으로 활용할 때 사용
launch 새로운 코루틴 생성 후 실행 X 결과가 필요없는 비동기 작업에 사용
async 새로운 코루틴 생성 후 실행 Deferred<T> await() 으로 결과값을 비동기적으로 전달 받을 수 있음
withContext 특정 Dispatcher에서 코드 실행 ( Default, IO, Main, Unconfined ) Block의 마지막 결과 현재 코루틴을 일시 중단하고, Dispatcher 내 작업이 완료된 이후에 코루틴을 재개 시킴