Goroutines in Kotlin

Here’s the translated content in Kotlin, following the original structure and explanation.

A goroutine is a lightweight thread of execution.

fun main() {
    fun f(from: String) {
        for (i in 0 until 3) {
            println("$from : $i")
        }
    }

    // Calling the function synchronously
    f("direct")

    // Calling the function in a separate coroutine
    val job = kotlinx.coroutines.GlobalScope.launch {
        f("coroutine")
    }

    // Calling an anonymous function in a separate coroutine
    val anonJob = kotlinx.coroutines.GlobalScope.launch {
        println("going")
    }

    // Wait for the coroutines to finish
    kotlinx.coroutines.runBlocking {
        kotlinx.coroutines.delay(1000L)
    }
    println("done")
}

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

f("direct")

To invoke this function in a coroutine, use launch { f(s) }. This new coroutine will execute concurrently with the calling one.

val job = kotlinx.coroutines.GlobalScope.launch {
    f("coroutine")
}

You can also start a coroutine for an anonymous function call.

val anonJob = kotlinx.coroutines.GlobalScope.launch {
    println("going")
}

Our two function calls are running asynchronously in separate coroutines now. Wait for them to finish (for a more robust approach, use a Job and join).

kotlinx.coroutines.runBlocking {
    kotlinx.coroutines.delay(1000L)
}
println("done")

When we run this program, we see the output of the blocking call first, then the output of the two coroutines. The coroutines’ output may be interleaved, because coroutines are being run concurrently by the Kotlin runtime.

$ kotlin RunCoroutines.kt
direct : 0
direct : 1
direct : 2
coroutine : 0
going
coroutine : 1
coroutine : 2
done

Next we’ll look at a complement to coroutines in concurrent Kotlin programs: channels.