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.
Suppose we have a function call f(s)
. Here’s how we’d call that in the usual way, running it synchronously.
To invoke this function asynchronously, we can use Grand Central Dispatch (GCD). This new dispatch asynchronously will execute concurrently with the calling one.
You can also start an asynchronous block for an anonymous function call.
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.
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.
Next, we’ll look at a complement to dispatch queues in concurrent Swift programs: combining them with other concurrency tools like DispatchGroup and OperationQueue.