How to know whether current Fiber is the root Fiber?

Hi, calling Fiber.yield without being in the context of a created
Fiber raises an error:

can’t yield from root fiber (FiberError)

It makes sense, of course. However I would like to know how to check
whether I’m into the root Fiber or not. The documentation doesn’t
provide a method for this purpose. Is there a way? I expected
something like Fiber#root?.

Thanks a lot.

How about catching the exception?

begin
Fiber.yield
rescue FiberError
puts “In root fiber…”
puts “… so I am going to do something different here.”
end

puts ‘executing rest of program’

–output:–
In root fiber…
… so I am going to do something different here.
executing rest of program

But looking at the Fiber docs, it looks like Fiber.current() will do
what you want:

====
Fiber.current() → fiber

Returns the current fiber. You need to require ‘fiber‘ before using this
method. If you are not running in the context of a fiber this method
will return the root fiber.

For example:

require ‘fiber’

root_fiber = Fiber.current

f = Fiber.new do
if Fiber.current.eql?(f)
puts ‘not root fiber’
else
puts ‘root fiber’
end

Fiber.yield “hello world”
end

f.resume

–output:–
not root fiber
root fiber

7stud – wrote in post #991816:

For example:

require ‘fiber’

root_fiber = Fiber.current

f = Fiber.new do
if Fiber.current.eql?(f)
puts ‘not root fiber’
else
puts ‘root fiber’
end

Fiber.yield “hello world”
end

f.resume

–output:–
not root fiber
root fiber

Instead, make that:

require ‘fiber’

root_fiber = Fiber.current

f = Fiber.new do
if Fiber.current.eql?(root_fiber)
puts ‘root fiber’
else
puts ‘not root fiber’
end

Fiber.yield “hello world”
end

f.resume

if Fiber.current.eql?(root_fiber)
puts ‘root fiber’
else
puts ‘not root fiber’
end

2011/4/8 7stud – [email protected]:

puts ‘not root fiber’
puts ‘not root fiber’
end

Great solution :slight_smile:

Thanks a lot.

On Mon, Apr 11, 2011 at 9:30 AM, Iaki Baz C. [email protected]
wrote:

else
else
puts ‘not root fiber’
end

Great solution :slight_smile:

You could even use #equal? instead of #eql? just in case #eql? is
overridden.

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs