Rohit Surwase
01/07/2019, 6:58 AMsuspendable lambdas + continuation + yeild
internally. I have also watched Exploring Coroutines in Kotlin by Venkat Subramariam several times. If Coroutines works the way it explained in the video then isn’t it like a single thread managing to execute multiple tasks depending upon the priority? Can we actually execute multiple tasks simultaneously on a single thread using Coroutines or it will be just managed by that thread? By managing I mean by using suspend + yeild, the thread will finish all tasks but time taken to finish all tasks will be combination of all individual taks.
Can anyone direct me to better understand internals of Coroutines?ckchen
01/07/2019, 8:08 AMBy managing I mean by using suspend + yeild, the thread will finish all tasks but time taken to finish all tasks will be combination of all individual taks.Basically yes. But the value of coroutines isn’t always about the performance. There is a difference between ‘asynchronous’ and ‘parallel/concurrent’. Coroutines help you to construct the program in an asynchronous way more easily. There might be parallelism (or not) between the coroutines created in the program. If so, using multiple threads to drive them is a bonus in the performance. I learned a lot from this video:
Rohit Surwase
01/07/2019, 8:12 AMstreetsofboston
01/07/2019, 3:11 PMRohit Surwase
01/07/2019, 4:29 PMsuspending lambdas + yeild + continuation
?streetsofboston
01/07/2019, 4:31 PMRohit Surwase
01/07/2019, 4:35 PMstreetsofboston
01/07/2019, 4:41 PMbdawg.io
01/07/2019, 4:55 PMContinuation
parameter as the final argument and your return type becomes Any
to return the final T
that it originally would return, or a special COROUTINE_SUSPENDED
constant to signal that the function has suspended execution, but needs another turn later.
The continuation holds a "label" which tells the function which part to execute next.
To illustrate what this looks like (simplified and not exactly how it's compiled):
suspend fun Deferred<Int>.sumWithAsync(val other: Int): Int = this.await() + other
Will be compiled as
fun Deferred<Int>.sumWithAsync(val other: Int, val cont: Continuation): Any {
when (cont.label) {
1 -> {
cont.waitFor(this@Deferred)
cont.label = 2
return COROUTINE_SUSPENDED
}
2 -> {
val a = this@Deferred.getCompleted()
return a + other
}
else -> error("invalid continuation")
}
}
again, that's not exactly how a suspending function is compiled (in particular cont.waitFor
is made up), but it's similar to emphasize how the function does return COROUTINE_SUSPENDED
so another function can take a turn using a threadRohit Surwase
01/07/2019, 5:31 PM