Why do we need fibers

后端 未结 2 1055
别跟我提以往
别跟我提以往 2021-01-29 17:51

For Fibers we have got classic example: generating of Fibonacci numbers

fib = Fiber.new do  
  x, y = 0, 1 
  loop do  
    Fiber.yield y 
    x,y = y,x+y 
  end         


        
2条回答
  •  渐次进展
    2021-01-29 18:17

    Unlike closures, which have a defined entry and exit point, fibers can preserve their state and return (yield) many times:

    f = Fiber.new do
      puts 'some code'
      param = Fiber.yield 'return' # sent parameter, received parameter
      puts "received param: #{param}"
      Fiber.yield #nothing sent, nothing received 
      puts 'etc'
    end
    
    puts f.resume
    f.resume 'param'
    f.resume
    

    prints this:

    some code
    return
    received param: param
    etc
    

    Implementation of this logic with other ruby features will be less readable.

    With this feature, good fibers usage is to do manual cooperative scheduling (as Threads replacement). Ilya Grigorik has a good example on how to turn an asynchronous library (eventmachine in this case) into what looks like a synchronous API without losing the advantages of IO-scheduling of the asynchronous execution. Here is the link.

提交回复
热议问题