class

Fiber

Inherits Reference / Object

A Fiber is a light-weight execution unit managed by the Crystal runtime.

It is conceptually similar to an operating system thread but with less overhead and completely internal to the Crystal process. The runtime includes a scheduler which schedules execution of fibers.

A Fiber has a stack size of 8 MiB which is usually also assigned to an operating system thread. But only 4KiB are actually allocated at first so the memory footprint is very small.

Communication between fibers is usually passed through Channel.

Cooperative

Fibers are cooperative. That means execution can only be drawn from a fiber when it offers it. It can't be interrupted in its execution at random. In order to make concurrency work, fibers must make sure to occasionally provide hooks for the scheduler to swap in other fibers. IO operations like reading from a file descriptor are natural implementations for this and the developer does not need to take further action on that. When IO access can't be served immediately by a buffer, the fiber will automatically wait and yield execution. When IO is ready it's going to be resumed through the event loop.

When a computation-intensive task has none or only rare IO operations, a fiber should explicitly offer to yield execution from time to time using Fiber.yield to break up tight loops. The frequency of this call depends on the application and concurrency model.

Event loop

The event loop is responsible for keeping track of sleeping fibers waiting for notifications that IO is ready or a timeout reached. When a fiber can be woken, the event loop enqueues it in the scheduler

Constructors

current

Returns the current fiber.

Source
new(name : String | Nil = nil, execution_context : ExecutionContext = ExecutionContext.current, &proc : -> ) : self

Creates a new Fiber instance.

When the fiber is executed, it runs proc in its context.

name is an optional and used only as an internal reference.

Source

Class methods

suspend

Suspends execution of the current fiber indefinitely.

Unlike Fiber.yield the current fiber is not automatically reenqueued and can only be resumed with an explicit call to #enqueue.

This is equivalent to sleep without a time.

This method is meant to be used in concurrency primitives. It's particularly useful if the fiber needs to wait for something to happen (for example an IO event, a message is ready in a channel, etc.) which triggers a re-enqueue.

Source
yield

Yields to the scheduler and allows it to swap execution to other waiting fibers.

This is equivalent to sleep 0.seconds. It gives the scheduler an option to interrupt the current fiber's execution. If no other fibers are ready to be resumed, it immediately resumes the current fiber.

This method is particularly useful to break up tight loops which are only computation intensive and don't offer natural opportunities for swapping fibers as with IO operations.

counter = 0
spawn name: "status" do
  loop do
    puts "Status: #{counter}"
    sleep(2.seconds)
  end
end

while counter < Int32::MAX
  counter += 1
  if counter % 1_000_000 == 0
    # Without this, there would never be an opportunity to resume the status fiber
    Fiber.yield
  end
end
Source

Instance methods

dead?

The fiber's proc has terminated, and the fiber is now considered dead. The fiber is impossible to resume, ever.

Source
enqueue

Adds this fiber to the scheduler's runnables queue for the current thread.

This signals to the scheduler that the fiber is eligible for being resumed the next time it has the opportunity to reschedule to another fiber. There are no guarantees when that will happen.

Source
execution_context
execution_context=(execution_context : ExecutionContext)
execution_context?
inspect(io : IO) : Nil

Appends a String representation of this object which includes its class name, its object address and the values of all instance variables.

class Person
  def initialize(@name : String, @age : Int32)
  end
end

Person.new("John", 32).inspect # => #<Person:0x10fd31f20 @name="John", @age=32>
Source
name

The name of the fiber, used as internal reference.

Source
name=(name : String | Nil)

The name of the fiber, used as internal reference.

Source
resumable?

The fiber's proc is currently not running and fully saved its context. The fiber can be resumed safely.

Source
resume

Immediately resumes execution of this fiber.

There are no provisions for resuming the current fiber (where this method is called). Unless it is explicitly added for rescheduling (for example using #enqueue) the current fiber won't ever reach any instructions after the call to this method.

fiber = Fiber.new do
  puts "in fiber"
end
fiber.resume
puts "never reached"
Source
running?

The fiber's proc is currently running or didn't fully save its context. The fiber can't be resumed.

Source
to_s(io : IO) : Nil

Appends a short String representation of this object which includes its class name and its object address.

class Person
  def initialize(@name : String, @age : Int32)
  end
end

Person.new("John", 32).to_s # => #<Person:0x10a199f20>
Source

Nested types