Method: Fiber#initialize

Defined in:
cont.c

#new(blocking: false, storage: true) {|*args| ... } ⇒ Object

Creates new Fiber. Initially, the fiber is not running and can be resumed with #resume. Arguments to the first #resume call will be passed to the block:

f = Fiber.new do |initial|
   current = initial
   loop do
     puts "current: #{current.inspect}"
     current = Fiber.yield
   end
end
f.resume(100)     # prints: current: 100
f.resume(1, 2, 3) # prints: current: [1, 2, 3]
f.resume          # prints: current: nil
# ... and so on ...

If blocking: false is passed to Fiber.new, and current thread has a Fiber.scheduler defined, the Fiber becomes non-blocking (see “Non-blocking Fibers” section in class docs).

If the storage is unspecified, the default is to inherit a copy of the storage from the current fiber. This is the same as specifying storage: true.

Fiber[:x] = 1
Fiber.new do
  Fiber[:x] # => 1
  Fiber[:x] = 2
end.resume
Fiber[:x] # => 1

If the given storage is nil, this function will lazy initialize the internal storage, which starts as an empty hash.

Fiber[:x] = "Hello World"
Fiber.new(storage: nil) do
  Fiber[:x] # nil
end

Otherwise, the given storage is used as the new fiber’s storage, and it must be an instance of Hash.

Explicitly using storage: true is currently experimental and may change in the future.

Yields:

  • (*args)


2293
2294
2295
2296
2297
# File 'cont.c', line 2293

static VALUE
rb_fiber_initialize(int argc, VALUE* argv, VALUE self)
{
    return rb_fiber_initialize_kw(argc, argv, self, rb_keyword_given_p());
}