Goroutines in Groovy

Based on the provided instructions, here’s the translated code and explanation to the target language, Groovy, in a format suitable for Hugo:

A goroutine is a lightweight thread of execution.

def f(from) {
    for (i in 0..<3) {
        println "${from} : ${i}"
    }
}

f("direct")

Thread.start {
    f("goroutine")
}

Thread.start {
    def msg = "going"
    println msg
}.join()

sleep 1000
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 new thread, use Thread.start { ... }. This new thread will execute concurrently with the calling one.

Thread.start {
    f("goroutine")
}

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

Thread.start {
    def msg = "going"
    println msg
}.join()

Our two function calls are running asynchronously in separate threads now. Wait for them to finish by using sleep or more advanced synchronization mechanisms.

sleep 1000
println "done"

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

$ groovy goroutines.groovy
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

Next, we’ll look at a complement to threads in concurrent programs: channels.