CodeGym /행동 /Kotlin SELF /withContext wa dispatcher reul coroutine eseo: silhaeng w...

withContext wa dispatcher reul coroutine eseo: silhaeng wichi jeonhwan

Kotlin SELF
레벨 53, 레슨 1
사용 가능

1. wae silhaeng wichireul jeonhwanhaeya halgga

Coroutineeul cheoeum sijakhal ttaen swipge hamjeonge ppajil su itseumnida: “suspendga iteuryeomyeon, mueosideun sseodo doego, geureom jayeonseureopge ppalleojigil geoya.” Hajiman yugeop, geureochi anhseumnida — coroutineun mulrireul museuriji mothamnida. CPUreul bupuneun code(gyesan, jeongnyeol, amchuk)ga itgo, I/Oreul gidarineun code(paile, neteuwokeu, DB, oebu system)ga itseumnida. withContextneun han gae coroutine aneseo “i jageun bu-buneun dareun goseseo haejwo”rago malhaneun bangbeobimyeo, byeoldo taskreul mandeulji ango gujoreul bokjaphage haji anhseumnida.

Oneul haeya hal haengdong gwannyeom: coroutineun gwanridoen gyeonggye wa myeonghwakhan gujore daehan geosigo, withContextneun silhaeng jogeon(dae-bubun dispatcher)reul lokallo, jeonggyohan bangsig-euro jeonhwanhaneun geosimnida.

“Coroutine context”rago hamyeon mwonga cheolhakjeogin geoseul tteoollil su itjiman, siljeoneun aju guchejeogin geosimnida: coroutinei jasin-gwa hamkke gajigo danineun seoljeong deul-ui jiphap. kotlinx.coroutineseseo context ui jungyohan elementneun yereumyeon Job (life cycle)gwa CoroutineDispatcher (eodiseo silhaenghaneunga)ga itseumnida — ige coroutine gibon model ui il-bubimnida.

Oneul uri ga gwan-sim isseoneun geos-eun juro dispatcherimnida. Dan-sunhwahaeseo (hajiman yuyonghage) ireoke saenggakhalsu itseumnida:

  • dispatcher neun dangsin codega eotteon threadeseo, geurigo eotteon pooleseo silhaengdoeneunji reul gwanrihamnida;
  • Dispatchers.Defaultneun botong CPU task(gyesan)e jeokhap합니다;
  • Dispatchers.IOneun botong I/O task(input/output daegi)e jeokhap합니다.

Meoritsokeseo modeun geoseul “cloud”cheoreom jiji anke mini schema reul geuryeobopsida:

flowchart TD
    A[Coroutine] --> B[CoroutineContext]
    B --> C[Job: saengmyeong ju-gi]
    B --> D[Dispatcher: eodiseo silhaeng]
    D --> E[Dispatchers.Default: CPU]
    D --> F[Dispatchers.IO: I/O]

Geuligo haeksim saenggak: withContextneun code blocke daehae silhaeng contextreul bakkumnida (dae-bubun dispatcher reul bakkum), geurigo “daeum coroutine hana reul tto sijeokhanda”ga 아닙니다.

2. withContextga mueoseul haneunji, geurigo wae suspendinji

withContextneun botong “silhaeng modeu”(ye: Dispatchers.IO)wa code blockeul inneun pyeongbeomhan ham-su cheoreom boimnida. Hajiman naebueseo jungyohan il-eul hamnida: hyeonjae coroutineeul ilsi jeongjihago, dareun contextro jeonhwanhae blockeul silhaenghan dwi, gyeolgwareul dashi dollyeojumnida.

Uimi sang-euro “dareun juchueuro gasa ppalli cha-reul mandeulgo, dashi dolawa dae-hwareul gyesokhae”raneun mal-gwa aju yusahamnida. Coroutineun ttokgat-eun coroutineigo, silhaeng seosa-neun yeonseokjeog-euro yujidoemyeo, danji il-ui il-bu-ga “dareun gos”eseo doem니다.

withContextga silhaeng-eul ilsi jeongjihal su itgi ttaemune suspend functionimnida. Ttaseo coroutine aneseona dareun suspend functioneseoman bulreul su itseumnida. Ilban functioneseo bulreobomyeon — compiler ga geuleohge mothage haneun geosi matseumnida.

“jjeo-geo-bon” mini example:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext

fun main() = runBlocking {
    val x: Int = withContext(Dispatchers.Default) {
        1 + 2 + 3
    }
    println("x = $x") // x = 6
}

Jom jom jal boseyo: withContext { ... }neun pyohyeonimnida. Blocki dollyeojun gapseul returnhamnida. Geuraeseo byeoldo ui 임시 변수 없이, geurigo byeongnyeolseongi pilyohaji anmyeon async/await eui jonjae eopsi, kotdeureun kkotdaero “ilbanjeog”uro sseul su itseumnida.

4. withContextneun byeongnyeolseong-ui iyagi-ga 아니다

Cho-bojae게 jaju naneun (geurigo aju in-ganjeogin) silsu: Dispatchers.IOreul bogo “aha, ige thread ingga? geureom byeongnyeollo doneun geoya”rago saenggak. Hajiman withContextneun “byeongnyeollo”ga anigo, “dareun goseseo, hajiman yeon-sokjeog-euro”imnida.

Hondonghaji angidorok, pyo ro bogyohamnida:

Tool mueoseul haneunga Return eonje sseununga
launch { ... }
haengdong-eul wihan saeroun coroutinereul saengseong
Job
byeongnyeollo silhaenghaeya 하고, naejung-e (pilyohamyeon) gidaril ttae
async { ... }
gyeol-gwareul wihan saeroun coroutinereul saengseong
Deferred<T>
gapseul byeongnyeollo gyosanhan dwi await()haeya hal ttae
withContext(ctx) { ... }
saeroun coroutineeul 만들지 않고, dareun contexteseo jageun bu-buneul silhaeng block ui result (T) yeon-sokjeog logic-i pilyohajiman, teukjeong 구간-eun dareun dispatcher’eseo silhaengdoeya hal ttae

Aju jjalbeun gyuchik: launch/asyncneun “doklip taskreul saengseong”, withContextneun “yeogi-eseo haneunde, dareun goseseo”.

5. thread ireumeul bogo jeonhwan-eul hwaginhaegi

Siljero mweonga 바뀌neunji (munseo-reul danji “믿는” geos-i anira) hwaginharyeomyeon, thread nameeul 출력하는 geosi yuyonghamnida. “thread reul saenggakhaji 말자”rago haetjiman, gakkeum han beon bogo na-myeon yuyonghaji-yo — yori han beon oven-i tteugeoun geoseul bogo na-myeon 매번 손으로 hwagin haji aneun geot cheoreomyo.

Jageun logger reul mandeureobopsida:

import kotlinx.coroutines.runBlocking

private fun log(msg: String) {
    println("$msg (thread=${Thread.currentThread().name})")
}

fun main() = runBlocking {
    log("start")
    log("still start")
}

Outputeun hwankyeong-e ttara dareul su itjiman, daerak ireonge boil geosimnida:

start (thread=main)
still start (thread=main)

Ije withContextreul chuga-hago, threadga bakkwineunji bopsida:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext

private fun log(msg: String) {
    println("$msg (thread=${Thread.currentThread().name})")
}

fun main() = runBlocking {
    log("before")
    withContext(Dispatchers.Default) {
        log("inside Default")
    }
    log("after")
}

Ganeung-han output (ye-si):

before (thread=main)
inside Default (thread=DefaultDispatcher-worker-1)
after (thread=main)

Yeogiseo jal못된 gyeollon-eul naerimyeon 안됩니다. Ige “saeroun coroutine-i saengseongdoeeotda”reul uimi haneun geosi 아닙니다. I bu-bun codega dareun dispatcher’로 widimdoe-eotgo, block kkeut-e dashi wonrae contextro dorawatdaneun uimiimnida.

6. mini app: console kassa, CPU wa I/O

Ye-siga “jin-gong coroutine in vacuum”ui jiphap-i doejianhge, han gaji seosa reul gyesokhaebopsida. Console app “kassa”ga itseodago haebopsida: jumun-e daehae 영수증(recepit)eul mandeumnida.

Naebueseo-neun du gaji ui junghyohan dan-gye-ga itseumnida:

  • “gagyeok bad-gi” — siljeoneun file/DB/network reading (즉 I/O)일 su itjiman, jigeum-eun Thread.sleepro simyulreiteu haebopsida;
  • “chong-aek gwa halin gyosan” — gyosan(CPU)imnida. I geos-eun Dispatchers.Defaulte du는 게 논리적입니다.

Meonje dan-sunhan data modeleul mandeureobopsida:

data class Order(
    val id: Int,
    val items: List<String>
)

data class Receipt(
    val orderId: Int,
    val total: Int
)

Ije “price list load”reul sseobopsida. Urideuri uidojeog-euro Thread.sleepreul sseoneun iyu-neun, ige blocking I/O imitatingiran geoseul gangjohaegi wiham입니다. Silje codeeseo-neun pa-il/DB queryga deureogessejiman, jigeum-eun dispatcher seontaeg ui aidi-ea ga haeksimimnida.

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun loadPriceList(): Map<String, Int> =
    withContext(Dispatchers.IO) {
        Thread.sleep(80) // I/O imitation
        mapOf("coffee" to 120, "tea" to 80, "cake" to 150)
    }

Ije total-eul gyosanhamnida. Yeogiseo-neun “u-i-do-jeog”uro gyosan ui wichi-ro Defaultreul sayonghamnida:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun calculateTotal(order: Order, prices: Map<String, Int>): Int =
    withContext(Dispatchers.Default) {
        order.items.sumOf { item -> prices[item] ?: 0 }
    }

Majimak-euro scenario reul han gae suspend functioneuro moa-bopsida:

suspend fun makeReceipt(order: Order): Receipt {
    val prices = loadPriceList()
    val total = calculateTotal(order, prices)
    return Receipt(orderId = order.id, total = total)
}

Poin: asyncreul mandeulji 않았고, awaitdo 하지 않았습니다. Byeongnyeolseongi pilyohaji 않습니다 — pilyohan geos-eun yeon-sokjeog logicijiman, dan-gye byeol로 “jeokjeolhan gos”eseo silhaengdoeneun 것입니다.

7. maineseo runBlockinggwa hamkke bomi

Bakkeseo bomyun codega geoui sync codecheoreom boigo, ige coroutinei saramdeurege sarangbatneun iyu jung 하나입니다: du beonjjae bunman-e meoriga kkeunhji anseumnida.

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val order = Order(id = 1, items = listOf("coffee", "cake"))
    val receipt = makeReceipt(order)

    println("Order #${receipt.orderId}, total=${receipt.total}")
    // Order #1, total=270
}

Yeogiseo ireon saenggak-e ppajil su itseumnida: “jamkkan, geureom multi-threading-eun eodisseo?” Geurigo ige jeongmal joheun jilmunimnida. Dap-eun ireoh습니다: multithreading-eun mokjeok-i anira 도구입니다. Uri ui mokjeok-eun I/Owa CPUga seoro banghae haji 않게 하고, jeokjeolhan pooleseo silhaengdoege 하는 것입니다. Geureomyeonseo code structure-reul dan-sunhage yujihaneun geosimnida.

8. withContext siljeon pattern

withContextreul 좁게 유지하세요: ige-neun scalpel이지, bucket이 아닙니다

Siljeoneseo withContextreul neomu aggressive-hage sseul su itseumnida: “proj-e-teu jeonbureul withContext(Dispatchers.IO)ro gamssa bolkka — hoksi do움

1
과제
Kotlin SELF, 레벨 53, 레슨 1
잠금
스레드 전환
스레드 전환
1
과제
Kotlin SELF, 레벨 53, 레슨 1
잠금
재시도 설정
재시도 설정
1
과제
Kotlin SELF, 레벨 53, 레슨 1
잠금
데이터와 통계
데이터와 통계
1
과제
Kotlin SELF, 레벨 53, 레슨 1
잠금
텍스트 정규화
텍스트 정규화
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION