Pablo Schmid
06/23/2021, 4:38 PMimport kotlinx.coroutines.*
import kotlin.system.*
fun main() = runBlocking {
val time = measureTimeMillis {
println("The answer is ${concurrentSum()} en ${Thread.currentThread()}")
}
println("Completed in $time ms en ${Thread.currentThread()}")
}
suspend fun concurrentSum(): Int = coroutineScope {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
one.await() + two.await()
}
suspend fun doSomethingUsefulOne(): Int {
println("1 in Thread ${Thread.currentThread()}")
delay(2000L) // pretend we are doing something useful here
return 13
}
suspend fun doSomethingUsefulTwo(): Int {
println("2 in Thread ${Thread.currentThread()}")
delay(2000L) // pretend we are doing something useful here, too
return 29
}
Zach Klippenstein (he/him) [MOD]
06/23/2021, 4:40 PMdiesieben07
06/23/2021, 4:41 PMdelay
call doesn't block the thread, it merely schedules your coroutine to wake up later. So both coroutines can be "waiting" at the same time, without blocking any threads at all.ephemient
06/23/2021, 4:42 PMZach Klippenstein (he/him) [MOD]
06/23/2021, 4:43 PMsuspend fun doSomethingUsefulOne(): Int {
println("1 in Thread ${Thread.currentThread()}")
delay(2000L) // pretend we are doing something useful here
return 13
}
is basically the same thing as:
fun doSomethingUsefulOne(callback: (Int) -> Unit) {
println("1 in Thread ${Thread.currentThread()}")
postAfterDelay(2000L) { callback(13) }
}
So doSomethingUsefulOne
returns right away, and leaves it up to the dispatcher to eventually finish executing the rest of the function.ephemient
06/23/2021, 4:44 PMdelay
) is a suspension point, where the dispatcher can stop running your function and do something elsePablo Schmid
06/23/2021, 6:00 PM