#1 ์์ ์ ์ฒ๋ฆฌ ๋ฐฉ์
#1-1 ๊ฐ์

์์ ๊ฐ์ ์ด 7๊ฐ์ ์์ ์ด ์๋ค๊ณ ๊ฐ์ ํ๋ค. ๊ฐ ์์ ์ด ์์ ์๊ฐ์ 5, 10, 15, 10, 20, 25, 5๋ค.
#1-2 ์ ํต์ ์ธ ๋ฐฉ๋ฒ

์ ํต์ ์ธ ๋ฐฉ๋ฒ์ ์ ํ์ (Serial)์ผ๋ก ์์ ์ ์ํํ๋ค.
#1-3 ์ ํต์ ์ธ ๋ฐฉ๋ฒ์ ๊ตฌํ
import kotlinx.coroutines.*
data class Food(val name: String, val cookingTimeInSeconds: Long)
suspend fun cook(food: Food) {
delay(1000 * food.cookingTimeInSeconds)
println("${food.name} ์๋ฃ")
}
fun main() {
val foods = arrayOf(
Food("๊ตญ๋ฐฅ", 5),
Food("๋ง๋", 10),
Food("๋น๋น๋ฐฅ", 15),
Food("ํ๋ฒ๊ฑฐ", 10),
Food("์นํจ", 20),
Food("ํผ์", 25),
Food("์๋์์น", 5),
)
val startTime = System.currentTimeMillis()
runBlocking {
for (food in foods) {
cook(food)
}
}
val endTime = System.currentTimeMillis()
println("์ด ์์ ์๊ฐ: ${(endTime - startTime) / 1000.0}์ด")
}
/* ์ถ๋ ฅ ๊ฒฐ๊ณผ
๊ตญ๋ฐฅ ์๋ฃ
๋ง๋ ์๋ฃ
๋น๋น๋ฐฅ ์๋ฃ
ํ๋ฒ๊ฑฐ ์๋ฃ
์นํจ ์๋ฃ
ํผ์ ์๋ฃ
์๋์์น ์๋ฃ
์ด ์์ ์๊ฐ: 90.168์ด
*/
์ ํต์ ์ธ ๋ฐฉ์์ ์์ ์ฒ๋ฆฌ๋ฅผ ์ฝ๋๋ก ๋ํ๋ด๋ฉด ์์ ๊ฐ๋ค.
#1-4 Parallel Decomposition

Parallel Decomposition์ ๋ฌธ์ ๋ฅผ ์์ ๋ถ๋ถ์ผ๋ก ๋๋์ด ๋์์ ์ฒ๋ฆฌํ๋ค. 7๊ฐ์ ์์ ์ค ๊ฐ์ฅ ์ค๋ ๊ฑธ๋ฆฌ๋ ์์ ์ด ๊ณง ์ ์ฒด ์์ ์๊ฐ์ด ๋๋ค. ์ด ๋ฐฉ๋ฒ์ ์ ์ฒด ์์ ์ ์๊ฐ์ ๋จ์ถ์ํจ๋ค. ๋ค์์ CPU ์ฝ์ด๋ฅผ ํจ์จ์ ์ผ๋ก ํ์ฉํด ๋๊ท๋ชจ ๋ฌธ์ ๋ฅผ ๋๋ ํด๊ฒฐํ ๊ฒ์ด๋ค. ์ฝํ๋ฆฐ์์๋ ์ฝ๋ฃจํด์ ์ด์ฉํด ๋ฌธ์ ๋ฅผ ๋ณ๋ ฌ๋ก ๋์ดํจ์ผ๋ก์จ Parallel Decomposition์ ๊ตฌํํ ์ ์๋ค.
#1-5 Parallel Decomposition์ ๊ตฌํ
import kotlinx.coroutines.*
data class Food(val name: String, val cookingTimeInSeconds: Long)
suspend fun cook(food: Food) {
delay(1000 * food.cookingTimeInSeconds)
println("${food.name} ์๋ฃ")
}
fun main() {
val foods = arrayOf(
Food("๊ตญ๋ฐฅ", 5),
Food("๋ง๋", 10),
Food("๋น๋น๋ฐฅ", 15),
Food("ํ๋ฒ๊ฑฐ", 10),
Food("์นํจ", 20),
Food("ํผ์", 25),
Food("์๋์์น", 5),
)
val startTime = System.currentTimeMillis()
runBlocking {
val cookingJobs: ArrayList<Job> = ArrayList()
for (food in foods) {
cookingJobs.add(launch {
cook(food)
})
}
/* runBlocking์ ํน์ฑ ๋์ ์๋ต ๊ฐ๋ฅ. ์ค๋ช
์ฐธ์กฐ.
for(cookingJob in cookingJobs) {
cookingJob.join()
}
*/
}
val endTime = System.currentTimeMillis()
println("์ด ์์ ์๊ฐ: ${(endTime - startTime) / 1000.0}์ด")
}
/* ์ถ๋ ฅ ๊ฒฐ๊ณผ
๊ตญ๋ฐฅ ์๋ฃ
์๋์์น ์๋ฃ
๋ง๋ ์๋ฃ
ํ๋ฒ๊ฑฐ ์๋ฃ
๋น๋น๋ฐฅ ์๋ฃ
์นํจ ์๋ฃ
ํผ์ ์๋ฃ
์ด ์์ ์๊ฐ: 25.104์ด
*/
Parallel Decomposition ๋ฐฉ์์ ์์ ์ฒ๋ฆฌ๋ฅผ ์ฝ๋๋ก ๋ํ๋ด๋ฉด ์์ ๊ฐ๋ค. ์ฝ๋ฃจํด์ ์ฌ์ฉํ๋ค. for๋ฌธ์ ๋ฐ๋ณต ํ์๋งํผ ์ฝ๋ฃจํด์ด ๋ณ๋ ฌ์ ์ผ๋ก ์ํ๋๋ค. ๊ฐ์ฅ ํฐ Food.cookingTimeInSeconds๋ ๊ณง ๋ชจ๋ ์ฝ๋ฃจํด์ด ์๋ฃ๋๋ ์๊ฐ์ด ๋๋ค. Job.join() ํจ์๋ฅผ ์๋ตํ ์ด์ ๋ runBlocking ํจ์๋ ์์ ์๋ ๋ชจ๋ ์ฝ๋ฃจํด์ด ๋๋์ผ ์ข ๋ฃ(์ด ๋งํฌ์ #3-2 ์ฐธ์กฐ)๋๊ธฐ ๋๋ฌธ์ด๋ค.
#2 ์์ฝ
๋ฌธ์ ๋ฅผ ๋๋ ์ ํธ๋ ๊ฑด ๋๊ตฌ๋ ํ ์ ์๋ค. ํ์ง๋ง, ๋๋ ๊ฑธ ๋ณ๋ ฌ์ ์ผ๋ก ํผ๋ค๋ฉด ์๊ธฐ๊ฐ ๋ฌ๋ผ์ง๋ค.
'๊นจ์ ๊ฐ๋ ๐ > Kotlin' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Kotlin] Coroutines - ViewModelScope (0) | 2024.02.20 |
---|---|
[Kotlin] Coroutines - ์ค๋ ๋ ์ ํ (0) | 2024.02.19 |
[Kotlin] Coroutines - Structured Concurrency (0) | 2024.02.16 |
[Kotlin] Couroutine - ์ค๋ ๋(Thread)์ ์ค๋ ๋ ํ(Thread Pool) (1) | 2024.02.15 |
[Kotlin] Coroutines - suspend ํค์๋ (0) | 2024.02.14 |