PHpullh
학습 라이브러리/Kotlin/병렬 분해 (Parallel Decomposition)

KOTLIN · 비동기

병렬 분해 (Parallel Decomposition)

asyncawaitAll로 작업을 병렬로 분해하고 결과를 합칩니다.

비동기중급asyncawaitAllparalleldecomposition

핵심 설명

asyncawaitAll로 작업을 병렬로 분해하고 결과를 합칩니다.

Kotlin code

import kotlinx.coroutines.*

data class ProductInfo(val name: String, val price: Int, val stock: Int)

suspend fun fetchName(id: Int): String {
    delay(300); return "상품-$id"
}
suspend fun fetchPrice(id: Int): Int {
    delay(200); return id * 1000
}
suspend fun fetchStock(id: Int): Int {
    delay(250); return (10..100).random()
}

suspend fun getProductInfo(id: Int): ProductInfo = coroutineScope {
    val name = async { fetchName(id) }
    val price = async { fetchPrice(id) }
    val stock = async { fetchStock(id) }
    ProductInfo(name.await(), price.await(), stock.await())
}

suspend fun getMultipleProducts(ids: List<Int>): List<ProductInfo> =
    coroutineScope {
        ids.map { id -> async { getProductInfo(id) } }.awaitAll()
    }

fun main() = runBlocking {
    val start = System.currentTimeMillis()

    val products = getMultipleProducts(listOf(1, 2, 3, 4, 5))
    products.forEach { println(it) }

    val elapsed = System.currentTimeMillis() - start
    println("소요 시간: ${elapsed}ms")  // ~300ms (병렬)
}

학습 팁

awaitAll()은 모든 Deferred의 결과를 기다립니다. 하나가 실패하면 나머지도 취소됩니다.

주의할 점

asynccoroutineScope 밖에서 사용하면 구조화된 동시성이 깨집니다. 항상 스코프 내에서 사용하세요.

자주 묻는 질문

병렬 분해 (Parallel Decomposition)란 무엇인가요?

async 와 awaitAll 로 작업을 병렬로 분해하고 결과를 합칩니다.

병렬 분해 (Parallel Decomposition) 학습 시 주의할 점은 무엇인가요?

async 를 coroutineScope 밖에서 사용하면 구조화된 동시성이 깨집니다. 항상 스코프 내에서 사용하세요.