Kotlin/포스팅

코루틴 빌더

짜집퍼박사(짜박) 2024. 1. 7. 13:47

코루틴 빌더는 코틀린에서 코루틴을 생성하고 관리하는 데 사용되는 함수 또는 키워드입니다. 코루틴 빌더는 launch, async, runBlocking 등이 있으며, 각각의 빌더는 특정한 용도로 사용됩니다. 아래에서 주요한 코루틴 빌더들에 대해 살펴보겠습니다.

 

1. launch

launch 빌더는 가장 기본적인 형태의 코루틴 빌더로, 비동기적으로 코드 블록을 실행합니다. 반환값이 없으며, 예외를 던지지 않는다면 코루틴의 실행이 완료되면 바로 다음 코드로 진행됩니다.

import kotlinx.coroutines.*

fun main() {
    GlobalScope.launch {
        // 비동기 작업
        delay(1000)
        println("Coroutine is running.")
    }

    println("Main thread is not blocked.")
    Thread.sleep(2000)
    println("End")
}

 

2. async

async 빌더는 launch와 비슷하지만 값을 반환할 수 있습니다. 또한 await 함수를 통해 해당 값이 사용 가능할 때까지 대기할 수 있습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred = async {
        // 비동기 작업
        delay(1000)
        "Result"
    }

    println("Main thread is not blocked.")
    val result = deferred.await()
    println("Result: $result")
}

 

3. runBlocking

runBlocking 빌더는 메인 함수나 테스트 코드에서 사용됩니다. 이 빌더는 블록 내의 코드가 모두 완료될 때까지 현재 스레드를 차단합니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        // 비동기 작업
        delay(1000)
        println("Coroutine is running.")
    }

    println("Main thread is blocked until coroutine is done.")
}

 

4. withContext

withContext 함수는 특정 디스패처에서 코드 블록을 실행합니다. 이는 launch와 비슷하지만, 현재 코루틴을 종료하고 새로운 코루틴을 실행하는 대신 현재 코루틴에서 지정된 디스패처로 전환됩니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        println("Start on ${Thread.currentThread().name}")

        withContext(Dispatchers.Default) {
            // 백그라운드 스레드에서 실행
            println("Running on ${Thread.currentThread().name}")
        }

        println("End on ${Thread.currentThread().name}")
    }
}

 

5. coroutineScope

coroutineScope 함수는 자신의 코루틴 범위 내에서 새로운 코루틴을 실행합니다. runBlocking과 유사하지만, runBlocking은 현재 스레드를 차단하는 데 반해 coroutineScope는 새로운 코루틴을 실행하면서 현재 스레드를 차단하지 않습니다.

import kotlinx.coroutines.*

suspend fun mySuspendingFunction() {
    coroutineScope {
        // 비동기 작업
        delay(1000)
        println("Coroutine is running.")
    }
}

fun main() = runBlocking {
    launch {
        mySuspendingFunction()
    }

    println("Main thread is not blocked.")
    delay(2000)
    println("End")
}

이러한 코루틴 빌더들을 통해 비동기적인 코드를 간결하고 효과적으로 작성할 수 있습니다. 각 빌더는 특정한 사용 사례에 맞게 선택하여 사용하면 됩니다.

 

With ChatGPT

'Kotlin > 포스팅' 카테고리의 다른 글

코루틴 구조적 동시성  (0) 2024.01.07
코루틴 영역  (0) 2024.01.07
코루틴과 일시 중단 함수  (0) 2024.01.07
코틀린 코루틴  (0) 2024.01.07
코틀린 쓰레드  (0) 2024.01.07