Goroutines in Racket

To run the program, we use the Racket REPL (Read-Eval-Print Loop):

$ racket goroutines.rkt
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

In Racket, concurrency is handled differently compared to the original language. Here we use the thread function to create concurrent tasks.

#lang racket

(require racket/thread)

(define (f from)
  (for ([i (in-range 3)])
    (printf "~a : ~a\n" from i)))

(define (main)
  (f "direct")

  (thread (lambda () (f "goroutine")))

  (thread (lambda ()
            (printf "going\n")))

  (sleep 1)
  (printf "done\n"))

(main)

In this example, the function f takes a string input and prints it along with a counter value from 0 to 2. The main function first executes f directly. It then starts two separate threads: one running f with the argument "goroutine", and another running an anonymous function that prints "going".

Finally, the main function sleeps for 1 second to allow the threads to complete their execution before printing "done".

The output of running the program will show the synchronous call first, followed by interleaved outputs from the concurrent threads, and finally, “done”. The exact order of the interleaved outputs may vary with each run because the threads are executed concurrently.