Search code examples
rubyfibers

Ruby: Get Fiber parent


Is it possible to retrieve the fiber which created the current fiber? It would suffice if I could get this information upon creation of a new Fiber.

Monkey-patching Fiber#new doesn't work, as calling Fiber#current results in "uninitialized fiber" error.


Solution

  • I finally found a way to get it working. If we redefine initialize it would fail as the internals won't initialize the fiber. It is however possible to alias it, create a new one, and then run the old one:

      class Fiber
        alias_method :old_init, :initialize
    
        def initialize
          old_init
          @parent = Fiber.current
        end
    
        def parent
          @parent
        end
      end
    

    Since the Fiber.current doesn't change until we execute resume on the fiber, we can safely copy a reference in the initializer.

    Now we can ask the system "Who's your grandpa?" Fiber.current.parent.parent.