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.

def f(from : String)
  3.times do |i|
    puts "#{from} : #{i}"
  end
end

# Call the function normally, executing it synchronously.
f("direct")

# To invoke this function in a fiber, use `spawn`.
spawn f("fiber")

# You can also start a fiber for an anonymous function.
spawn do 
  puts "going"
end

# 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).
sleep 1

puts "done"

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 fiber, use spawn f(s). This new fiber will execute concurrently with the calling one.

spawn f("fiber")

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

spawn do 
  puts "going"
end

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).

sleep 1
puts "done"

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.

$ crystal run fibers.cr
direct : 0
direct : 1
direct : 2
fiber : 0
going
fiber : 1
fiber : 2
done

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.