반응형
이 게시물은 다음 링크를 참조하여 학습했습니다
Composing suspending functions | Kotlin
kotlinlang.org
이번 게시물에서는 suspending functions를 다루는 여러가지 방법에 대해 이야기하고자 한다.
coroutine에서 동시성을 제공한다고 했는데, 해당 내용을 이번 게시물에서 다룬다고 이해하면 된다.
아래 설명할 예제들은 이 코드를 기반으로 설명하려 한다.
suspend fun doSomethingUsefulOne(): Int{
delay(1000L)
return 13
}
suspend fun doSomethingUsefulTwo() :Int{
delay(1000L)
return 29
}
1. 순차적 실행
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun main() = runBlocking {
val time = measureTimeMillis {
val one = doSomeThingUsefulOne()
val two = doSomeThingUsefulTwo()
println("The answer is ${one + two}")
}
println("Completed in $time ms")
}
위 코드를 실행하면 아래 결과값을 얻을 수 있다.
The answer is 42 [main]
Completed in 2027 ms [main]
비동기 연산을 동기적으로(순차) 실행한 것을 볼 수 있다.
즉, one을 실행 완료한 후에 two를 실행한 모습을 볼 수 있다.
2. 동시적 실행
그런데 위 예제에서 one과 two가 전혀 관련없을 경우에 위 예제는 비효율적이다.
다시 말하면 one의 결과가 two의 연산에 아무런 관계가 없을 때, 동시에 실행한다면 시간을 절약할 수 있다.
이 때 , async{ ... } await()을 사용하면 된다.
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun main() = runBlocking {
val time = measureTimeMillis {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
위 코드를 실행하면 아래 결과를 얻을 수 있다.
The answer is 42 [main]
Completed in 1032 ms [main]
one과 two를 동시적으로 수행하여 시간이 단축된 모습을 볼 수 있다.
3. async의 지연
async는 시작시점을 지정해줄수 있다.
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun main() = runBlocking {
val time = measureTimeMillis {
val one = async(start = CoroutineStart.LAZY){ doSomeThingUsefulOne() }
val two = async(start = CoroutineStart.LAZY){ doSomeThingUsefulTwo() }
one.start()
two.start()
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
위 코드는 one과 two를 동시에 실행해서 2번예제와 동일한 결과를 얻지만, 그게 아니라면 1번예제와 동일한 결과를 얻을 것이다.
상황에 맞게 시작 시점을 지정해서 응답받을 시간을 조절할 수 있다!
반응형
'Legacy' 카테고리의 다른 글
[Kotlin #15] Coroutines - Coroutine Context and Dispatchers (0) | 2022.06.15 |
---|---|
[Kotlin #14] Coroutines - Coroutines under the hood (0) | 2022.06.15 |
[Kotlin #12] Coroutines - Cancellation and timeouts (0) | 2022.06.09 |
[Kotlin #11] Coroutines (0) | 2022.06.09 |
[Kotlin #10] Null Safety (0) | 2022.06.02 |