简体   繁体   中英

Kotlin Coroutine Execution Order Same Thread

I have come across some code that creates a CoroutineScope with a single thread context

val serialThreadContext = newSingleThreadContext("mysinglethreadcontext")
fun myScope(): CoroutineScope = CoroutineScope(serialThreadContext)

Then elsewhere in the code base, coroutines are launched in this scope...

myScope().launch {
   someOtherMethod()
   ...
}

From what I understand, all of these created coroutines will be scheduled on the same thread, but I can't find any specific documentation on order of execution or suspension.

This raises the following questions in my mind:

  1. if someOtherMethod doesn't contain any suspend functions, can this coroutine still be suspended by the thread?

  2. is there any guaranteed order of execution when the thread pulls the coroutine from the scheduler?

  1. Coroutines can only be suspended at suspend functions. Once someOtherMethod is invoked, if it is not a suspend function, there is no way to avoid waiting for that function to return before the thread can be freed up by suspending. Note that a function being marked suspend still doesn't mean it will necessarily suspend the coroutine calling it. If it doesn't internally do suspending work on some other dispatcher, it will still be occupying your calling thread.

  2. There is no guarantee of execution order. You should not rely on a single-threaded dispatcher to try to queue work in order. See my answer here for an example of how you could create a work queue with a Channel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM