Search code examples
asynchronouskotlincoroutinekotlin-coroutinessimultaneous

Invoking a function twice by two coroutines simultaneously


How to run a function twice by two coroutines simultaneously? I tried with this code:

import kotlinx.coroutines.*

fun main() = runBlocking<Unit> {
    launch {
        calculate("first")
    }
    launch {
        calculate("second")
    }
}

fun calculate(name: String) {
    var value = 0
    for (x in 1..1_000){
        value += 1
        if(x % 100 == 0){
            println("calculating $x for $name")
        }
    }
}

but second coroutine waits until first coroutine leaves the function, to run it!

How am i gonna to do such thing?


Solution

  • runBlocking uses an event loop as a default for the coroutine dispatcher. With an event loop only one coroutine can run on the event thread simultaneously.

    You can specify any other dispatcher that uses a thread pool, e.g. Dispatchers.Default, to run coroutines simultaneously.

    fun main() = runBlocking<Unit>(Dispatchers.Default) {
        launch {
            calculate("first")
        }
        launch {
            calculate("second")
        }
    }