1. Sogae
Koryutin-eul sseugi sijakhago nameun swipge han gaji hwansang-e ppajipnida: “Igeun seuredeu-ga anieo, geureom seuredeu-ui wiheomdo eopgetji.” Hajiman (eotteomyeon haengbokhage-do — geureom an jaemisseosseul tenikka) koryutin-eun chungbunhi silje-ro gyeongjaeng jeog-euro silhaengdoel su itsgo, Dispatchers.Defaulteseoneun seuredeu pule seo pyeonghaeng-eurodo dongjakhamnida. Jeuk, du gae-ui koryutin-i dareun CPU core-eseo jeongmal-ro dongsi-e yeoreobun-ui kodeureul silhaenghal su itsseumnida.
Koryutin gwallyeon gongshik jaryo-eseoneun koryutin-i builders (launch, async) ro silhaengdoemyeo, geu haengdong-eun context-e uihayeo gyeoljeongdoenda-go gangjo합니다. geu jung-eseodo “eodiseo koryutin-i dallyeoganeunji” reul gyeoljeonghaneun CoroutineDispatcher ga jungyohamnida.
Gyeongjaeng jeog silhaeng-i isseumyeon, deutgo sipji anheun “yeong-wonhan dan-gol” munje gajang-gyo: race, race, geurigo tto race ga deungsanghamnida. Koryutin-eun hyeondaejeog이고 pyeonrihajiman, scheduler-ui beopchik-eul jiwool sun eopseumnida.
Shared mutable state
Race condition-e daehae bulpyeonghagi jeone, yong-eo reul jeongrihae-ya 합니다. Shared mutable state neun “gong-yu doeneun byeongyeong ganeun sangtae” imnida. Jeuk, eotteon data ga yeoreo koryutin-eseo dongsi-e sseugi ganeunghage jeopgeun doeneun gyeong-u 입니다. Yeogiseo jungyohan geon “sseugi” 입니다: modu-ga ikgi-man hamyeon botong deo anjeonhajiman (geuraedo geu juwi-e deungjanghaneun yahoanhang-i itgireul hamnida).
Shared mutable state-ui ye-ro neun var counter = 0 gateun byeonsu reul manhi koryutin-i dongsi-e jeungga-sikineun gyeong-u imnida. tto-neun var balance = 100 eseo yeoreo koryutin-i dongsi-e don-eul chulgeumharyeogo si-do-haneun gyeong-u. tto-neun yeoreo koryutin-i element reul chu-gahaneun dong-an dareun koryutin-i geureul sunhoe-haneun MutableList do ye-ga doel su itsseumnida.
Shared mutable state-ui munje-neun “kodeu nonri” ttaemun-e manggajineun geos-i anira, teukjeong sungan-e silhaeng dan-gye-deuri eotteoke seokyeo-deureogasseuneunya-e ttara manggajindaneun geos imnida. geurigo geu geos-eun beolsseo programming gati-ji ango, oneul eotteon nal-eun aegyo-reul bu릴지 kkaetip si-reulji gajang jageun gom-i decide-haneun goyangi-wa hyeopsanghaneun deuthan gibun-i doemnida.
2. Habseong yeonsan: eodiseo race ga sum-eo itna
counter++ neun han beon-ui yeonsan-i 아니다
Jigeum buteo chobo-ui insaeng-eul kkaeneun sungan-i 옵니다 (kkeutkkaji chobo-ga anirado gakkeum): counter++ neun han beon-ui yeonsan-cheoreom boyeojiman, uimi-sang euro-neun choesohan 세 dan-gye imnida:
1) memory 에서 counter reul register/byeonsu 로 ilgeunda,
2) 1 reul deohanda,
3) saeroun 값을 counter e dasi sseunda.
I dan-gye-deul-eul han koryutin-i haenghamyeon muneje eopseumnida. Hajiman du koryutin-i dongsi-e haenghamyeon, “seoro-ui sseugi” reul balbapul su itsseumnida.
Duge koryutin modu-ga counter = 10 eul ilgeoss다고 sangsanghae boseyo. modu-ga 10 + 1 eul gyesanhaessgo, modu-ga 11 eul sseobeoryeosseumnida. gyeolgwa: du beon increment haeya hal geos-i han beon-man doeeotseumnida. eotteon “magi” do anigo, geunyang nonri-ga “deopeoss-eo sseowojim” (overwrite) doeeot-eul 뿐 입니다.
Da-eum jageun yeje-neun botong pyeongbeomhan noteubuk-eseodo munje-reul jal boyeojumnida:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
var counter = 0
val jobs = List(1_000) {
launch(Dispatchers.Default) {
counter++ // race: read → add → write
}
}
jobs.forEach { it.join() }
println(counter) // often < 1000
}
Un-i joh-eumyeon 972, 998, 1000 gacheoreom boyeojul geos imnida… geurigo i “gakkeum 1000” i baro tto dareun jeongshin jeog go통-ui woncheonimnida. wae냐하면 “gakkeum-eun an teojineun” bug-neun botong demo ttae sangsa/ap-e seo balsaenghamnida.
Wae race neun magicheoreom boyeona
Race condition-ui gajang burpyeonhan teukjing-eun ye측 불가능함 입니다. Seuredeu-wa koryutin scheduler-neun (dan순화하면) nugu-ege eonje CPU sigan-eul julji gyeoljeonghamnida. geu gyeoljeong-eun ppalli, jaju, geurigo yeoreobun-ui uigyeon-eul mudji ango ir-eonam니다. gat-eun machine, gat-eun 실행-eseo-neun han beon-ui 섞임(interleaving) i, daeum 실행-eseo-neun dareun 섞임 i saenggimnida. geurigo println eul han 줄 chuga-hamyeon modu-ga “gyeolham-i go쳐jim” cheoreom boyeol su itsseumnida (출력-eun 느리고, seokim-i dareuge doeni).
I geos-eul son-euro 느끼려면, gat-eun 실험-eul yeoreo beon dollyeoseo gyeolgwa-ga eotteoke “heulleodeumyeo” baraeneunji bomyeon doemnida:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
repeat(5) { attempt ->
var counter = 0
val jobs = List(1_000) {
launch(Dispatchers.Default) { counter++ }
}
jobs.forEach { it.join() }
println("attempt=$attempt counter=$counter") // attempts differ
}
}
Yeogiseo jungyohan geon “gakkeum 1000 i anira” ga anira, mae beon gyeolgwa-ga dareul su itda neun geot imnida. i geosi race-ui gajang keun gamjeong jeog sign imnida: nonri-neun hanagana, hyeonsil-eun 매번 saerop습니다.
Check-then-act: “geomsa-haego → haengdong” hamjeong
counter++ ga jeontongjeog race ra면, check-then-act neun deo gyoalhan chincheok imnida. i geos-eun cheoeum-e 조건-eul 검사하고, geu daeum-e haengdong-eul 하니, “na-neun geomsa-haess으니 anjeonhagetji” 라고 느끼게 만드는 패턴입니다. Hajiman geomsa wa haengdong 사이-e dareun koryutin-i kkeun-eodeureo-wa sangtae-reul bakkul su itsseumnida.
Jageun scenario reul sangsanghaebopsida: tiket-eul paneun jageun “kassa”. tickets = 1 i라는 byeonsu-ga 있고, du koryutin-i tiket-eul sa-ryeogo 합니다: “tickets ga isseumyeon 1 gamsa”.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
var tickets = 1
val j1 = launch(Dispatchers.Default) {
if (tickets > 0) {
delay(10) // increase chance of interleaving
tickets -= 1
}
}
val j2 = launch(Dispatchers.Default) {
if (tickets > 0) {
delay(10)
tickets -= 1
}
}
j1.join()
j2.join()
println("tickets=$tickets") // can become -1
}
Haeksim-eun, du koryutin modu-ga tickets > 0 geomsa-reul 통과할 su 있다는 점 입니다. geomsa 시점-e tickets ga ajik 1 i기 때문입니다. geu daeum du koryutin modu-ga 차감-eul 실행하면 -1 i 됩니다. 현실-eseo-neun “han jari-e du jang-eul pal-assda” 라고 부르고, 프로그래밍-eseo-neun “돈 kwa reputaion-eul kkaemeogeun bug-reul saengseonghaessda” 라고 할 su 있겠습니다.
Juyeohal 점: yeogiseo munje-neun delay ga 아닙니다. delay neun geunyang race-reul deo jal 보이게 만들 뿐입니다. Race-neun geu-ga 없어도 존재합니다 — danji deo jal sum-eul 뿐 입니다.
3. Invariant wa critical section
Mueoseul bogo boho-haneunga
Gyeongjaengseong 이야기가 나오면, “algesseo, geureom modu boho-haji” 라고 말하고 싶-eojijiman, geureon banghyang-eun kodeu-ga neujeorijigeona, 아니면 ihaehagi himdeun 죽처럼 bae-eo 버리는 길 입니다. Geuraeseo jungyohan dan-eo han ga-reul 도입해야 합니다: invariant.
Invariant neun gyeongjaengseong-i itde라도 hangsang cham이어야 하는 무결성 규칙입니다. uri kassa yeje-eseo-neun da-eum gwa gateun invariant-reul saeng-gakhal su 있습니다:
| Sangtae | Invariant (gyuchik) | Wae jungyohan-ga |
|---|---|---|
|
|
issneun 것보다 deo manhi pal su eopda |
|
|
tiket su-ga “gongjung-eseo saenggyeonaseo” neun an 된다 |
|
|
gyuchik-sang geumji-doeneun minus-neun an 된다 |
Invariant-ui gajang yuyonghan 점-eun, da-eum jilmun-e daedabhae jundaneun geot imnida: “eoneu bu-bun kodeu-reul jeoldae jjo개-myeon 안 되는가?” Jeuk, eoneu nonri-reul dareun koryutin-i junggan-e “tteo-eotteur릴” su eopge 만들어야 하는지 입니다.
Ye-reul 들어 check-then-act-eseo invariant-ga gajang jaju 깨지는 이유-neun, geomsa와 변경이 uimi-sang han “atomic” block이어야 하기 때문입니다: “geomsa하고 geu sungan baro haengdonghae, geu 사이-e 제어를 넘기지 않는다.”
“Choeso dan-wi” reul chajneun beob
Critical section i라는 yong-eo-neun dangjang bunker-reul jiseul geot 같은 느낌이지만, uimi-neun 더 단순합니다: critical section-eun “지금 이 순간엔 딱 하나만” 실행되는 것처럼 동작해야 하는 kodeu 구간입니다. Jeuk, han koryutin-i i 구간-eul 실행하는 동안, dareun koryutin-eun gat-eun sangtae-e daehae 충돌하는 구간을 dongsi-e 실행하면 안 됩니다.
Hajiman i gang-ui-eseo jungyohan geon “critical section-eul eotteoke boho-haneun-ga” (도구들은 나중에) ga 아니라, “eotteoke olbareuge gubunhaneun-ga” 입니다. Yeogiseo “yeonpil로 kodeu geu-eoge pyo-si-haegi” gateun yeonseub-i yuyong합니다:
Gong-yu sangtae-reul 읽고 쓰는 구간-eul j잡고, 스스로-ege mud-eoseyo: “man약 딱 i 줄 직후-e na-ga 끊기면, invariant-ga imi 깨질 su 있나?” 만약 그렇다면 critical section 경계가 잘못 잡힌 것이고, 의존하는 단계들을 포함하도록 block-eul 더 넓혀야 합니다.
tickets ui gyeong-u-neun da-eum-cheoreom 보입니다:
if (tickets > 0) { // read tickets and decide
tickets -= 1 // write tickets
}
Du 줄 사이-e서 끊기면, dareun koryutin-i gat-eun (예전) 값-euro tto gyeoljeonghae beoril su 있습니다. Geuraeseo du 줄-eun uimi-sang han 덩어리 — tiket 구매라는 han beon-ui nonri jeog yeonsan — 로 봐야 합니다.
Chobo-reul wihan joh-eun gyuchik: nonri-ga “ilgeossda → gyeoljeonghaessda → sseossda” 로 boyeomyeon, geugeon almost surely critical section 후보입니다. Kodeu-ga dalli du 줄
GO TO FULL VERSION