Goroutines in Nim

Based on the provided instructions, here is the translated code and explanation in Nim:

Example: Goroutines (translated to Nim)

A goroutine is a lightweight thread of execution.

import os

proc f(from: string) =
  for i in 0..2:
    echo from & " : " & $i

proc main() =
  # This runs f synchronously
  f("direct")

  # This runs f asynchronously with threads
  # Threads are the closest concept in Nim to goroutines
  var th: Thread[void]
  createThread(th, f, "thread")

  # Anonymous procedure call in a thread
  var th2: Thread[void]
  proc anon(msg: string) =
    echo msg
  createThread(th2, anon, "going")
  
  # Wait for the threads to complete
  sleep(1000)
  echo "done"

main()

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 thread, use createThread. This new thread will execute concurrently with the calling one.

var th: Thread[void]
createThread(th, f, "thread")

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

var th2: Thread[void]
proc anon(msg: string) =
  echo msg
createThread(th2, anon, "going")

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

sleep(1000)
echo "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 Nim runtime.