Goroutines in F#

A goroutine is a lightweight thread of execution.

open System
open System.Threading

let f (from: string) =
    for i in 0 .. 2 do
        printfn "%s: %d" from i

[<EntryPoint>]
let main argv =
    // Calling the function synchronously.
    f "Direct"

    // Starting a thread to run the function concurrently.
    let thread = new Thread(ThreadStart(fun () -> f "Goroutine"))
    thread.Start()

    // Starting a thread with an anonymous function.
    let threadAnonymous = new Thread(ThreadStart(fun () -> printfn "going"))
    threadAnonymous.Start()

    // Waiting for the threads to finish.
    Thread.Sleep(1000)
    printfn "done"
    
    0 // return an integer exit code

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

let thread = new Thread(ThreadStart(fun () -> f "Goroutine"))
thread.Start()

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

let threadAnonymous = new Thread(ThreadStart(fun () -> printfn "going"))
threadAnonymous.Start()

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

Thread.Sleep(1000)
printfn "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.