Goroutines in Crystal
Based on the provided input, here is the translation of the Go code example into Crystal with the explanation in Markdown format:
Concurrency with Fibers
A fiber is a lightweight thread of execution. Let’s see an example of using fibers.
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 in a fiber, use spawn f(s)
. This new fiber will execute concurrently with the calling one.
You can also start a fiber for an anonymous function call.
Our two function calls are running asynchronously in separate fibers now. Wait for them to finish (to make this example simple, we are using sleep).
When we run this program, we see the output of the blocking call first, then the output of the two fibers. The fibers’ output may be interleaved because fibers are being run concurrently by the Crystal runtime.
Next, we’ll look at a complement to fibers in concurrent Crystal programs: Channels.
This example demonstrates how to use fibers in Crystal to run functions concurrently.