Goroutines in Swift

Based on the Go code example interpreting it into Swift and providing an explanation in Markdown format for Hugo:


A goroutine is a lightweight thread of execution. We will see how we can achieve similar behavior in Swift with dispatch queues.

import Foundation

func f(from: String) {
    for i in 0..<3 {
        print("\(from) : \(i)")
    }
}

func main() {
    // Running the function synchronously
    f(from: "direct")
    
    // Running the function asynchronously using GCD
    DispatchQueue.global().async {
        f(from: "goroutine")
    }
    
    // Running an anonymous function asynchronously using GCD
    DispatchQueue.global().async {
        print("going")
    }
    
    // Sleep a bit to allow async functions to finish
    Thread.sleep(forTimeInterval: 1.0)
    print("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(from: "direct")

To invoke this function asynchronously, we can use Grand Central Dispatch (GCD). This new dispatch asynchronously will execute concurrently with the calling one.

DispatchQueue.global().async {
    f(from: "goroutine")
}

You can also start an asynchronous block for an anonymous function call.

DispatchQueue.global().async {
    print("going")
}

Our two function calls are running asynchronously in separate dispatch queues now. Wait for them to finish. Here we have used Thread.sleep for simplicity, but in a more robust approach, you might use DispatchGroup.

Thread.sleep(forTimeInterval: 1.0)
print("done")

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

$ swift run
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

Next, we’ll look at a complement to dispatch queues in concurrent Swift programs: combining them with other concurrency tools like DispatchGroup and OperationQueue.