I’m curious about the correct way to make coroutines run in parallel on different threads. Here’s my code using runBlocking
, but both coroutines execute on the main thread.
suspend fun main() = runBlocking {
println("[${Thread.currentThread().name}]")
launch {
delay(500)
println("[${Thread.currentThread().name}] launch #1")
}
launch {
delay(500)
println("[${Thread.currentThread().name}] launch #2")
}
delay(1000)
}
[main @coroutine#1]
[main @coroutine#2] launch #1
[main @coroutine#3] launch #2
Are both coroutines started with launch executing on the main thread because they inherit the context from runBlocking
?
And here’s some code using coroutineScope
. In this case, the coroutines launched with launch
are executed on the same worker thread.
suspend fun main() = coroutineScope {
println("[${Thread.currentThread().name}]")
launch {
delay(500)
println("[${Thread.currentThread().name}] launch #1")
}
launch {
delay(500)
println("[${Thread.currentThread().name}] launch #2")
}
delay(1000)
}
[main]
[DefaultDispatcher-worker-1 @coroutine#2] launch #2
[DefaultDispatcher-worker-1 @coroutine#1] launch #1
Unlike when using runBlocking
, why aren’t they executed on the main thread in this case?
Lastly, here’s code executing coroutines using Dispatchers.Default
. In this case, the two coroutines run on different threads. (The result is the same whether using runBlocking
or coroutineScope
.)
suspend fun main() = runBlocking {
println("[${Thread.currentThread().name}]")
launch(Dispatchers.Default) {
delay(500)
println("[${Thread.currentThread().name}] launch #1")
}
launch(Dispatchers.Default) {
delay(500)
println("[${Thread.currentThread().name}] launch #2")
}
delay(1000)
}
[main]
[DefaultDispatcher-worker-2 @coroutine#1] launch #1
[DefaultDispatcher-worker-1 @coroutine#2] launch #2
On a multi-core system, when using Dispatchers.Default
or Dispatchers.IO
, can I guarantee that the two coroutines will always run in parallel on different threads? Conversely, if I don’t specify the Dispatchers, can the coroutines execute on the same thread?
I seem to have asked too many questions. To summarize:
- Why do two coroutines launched under
runBlocking
both execute on the main thread? - Why do two coroutines launched under
coroutineScope
execute on the same worker thread? And why, unlike when usingrunBlocking
, don’t they execute on the main thread? - When specifying a Dispatcher (like
Dispatchers.Default
orDispatchers.IO
), can I guarantee that two coroutines will execute in parallel on different threads?
Thank you.