What are Fibers in Ruby and how to use them?

Asked

Viewed 58 times

4

I was trying to do a reverse proxy using Webrick when I discovered that the version I had installed from Webrick did not contain the methods necessary to make a "chunked" worthy reading. So I applied the following Monkey patch:

class WEBrick::HTTPRequest
    ##
    # Prepares the HTTPRequest object for use as the
    # source for IO.copy_stream

    def body_reader
        @body_tmp = []
        @body_rd = Fiber.new do
            body do |buf|
                @body_tmp << buf
                Fiber.yield
            end
        end
        @body_rd.resume # grab the first chunk and yield
        self
    end

    # for IO.copy_stream.  Note: we may return a larger string than +size+
    # here; but IO.copy_stream does not care.
    def readpartial(size, buf = ''.b) # :nodoc
        res = @body_tmp.shift or raise EOFError, 'end of file reached'
        buf.replace(res)
        res.clear
        @body_rd.resume # get more chunks
        buf
    end
end

I saw that he uses Fiber to do the reading on Hunks, but did not understand what class Fiber is neither what the Fiber.yield different from a simple yield.

That one Fiber has some purpose with threads? Your big gain is in using it with yields, or has any other use case other than this?

1 answer

1

The Fiber is a class in the standard Ruby library that implements a cooperative, or preemptive, competition mechanism. It is worth remembering that although the context of the question is about Fibers in Ruby, this concept is not unique to the language.

The difference in general and generalized terms is that threads use a preemptive scheduling, while Fibers use cooperative scheduling.

The workflow in a thread can be interrupted at any time, and another thread starts to rotate. As for Fibers, the flow of tasks only changes if you explicitly ask it to change, which is the yield in question.

The big gain with Fibers instead of threads, is that with threads the programmer needs to be hyper careful with race conditions and other similar problems. Already with Fibers, the control is in the hands of the programmer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.