Provides a non-preemptive lightweight thread (fiber), also known as a coroutine or a semicoroutine in other programming languages.
A fiber's context does not change unless explicitly specified. A fiber also has a parentage. The fiber that called Fiber#resume is the parent, and the fiber that was called is the child. Transitions that destroy parentage (for example, switching to a parent fiber of one's own parent) are not allowed. They will result in a FiberError exception. The following two actions are possible:
This parentage is dynamic, and is dissolved upon switching the context to the parent fiber.
When a fiber ends, the context switches to its parent.
Fibers are used to switch the context to another routine at a processing point and to resume from that point. Fiber.new creates a fiber along with the provided block. Calling Fiber#resume for a created fiber switches the context. Calling Fiber.yield within the child fiber's block switches the context to the parent. The arguments of Fiber.yield are the return values of Fiber#resume on the parent.
f = Fiber.new do n = 0 loop do Fiber.yield(n) n += 1 end end 5.times do p f.resume end #=> 0 1 2 3 4
Creates and returns a fiber along with the provided block. The block is executed with the provided arguments as its arguments.
The context switches to the parent when the block ends. The block's evaluated value is returned at that time.
a = nil f = Fiber.new do |obj| a = obj :hoge end b = f.resume(:foo) p a #=> :foo p b #=> :hoge
Switches the context to the parent of the current fiber.
The yield method returns the provided arguments to Fiber#resume when switching the context.
For arg, specify the object to pass to the parent of the current fiber.
a = nil f = Fiber.new do a = Fiber.yield() end f.resume() f.resume(:foo) p a #=> :foo
Switches the context to the fiber represented by self, which is the child of the fiber that called resume.
The resume method returns the arguments provided to Fiber.yield when switching the context.
For arg, specify the object to pass to the fiber represented by self.
f = Fiber.new do Fiber.yield(:hoge) end a = f.resume() f.resume() p b #=> :hoge