Skip to content

Instantly share code, notes, and snippets.

@thash
Last active August 29, 2015 14:06
Show Gist options
  • Save thash/c8a3c9233cb0c2a61f07 to your computer and use it in GitHub Desktop.
Save thash/c8a3c9233cb0c2a61f07 to your computer and use it in GitHub Desktop.
AllAbout 019 Fiber
fibonacci = Fiber.new do
x, y = 0, 1
loop do
Fiber.yield y # yieldに渡した値がresumeの返り値となる
x, y = y, x + y
end
end
puts fibonacci.resume #=> 1
puts fibonacci.resume #=> 1
puts fibonacci.resume #=> 2
puts fibonacci.resume #=> 3
puts fibonacci.resume #=> 5
puts fibonacci.resume #=> 8
puts fibonacci.resume #=> 13
Fiber.new
# => ArgumentError: tried to create Proc object without a block
f = Fiber.new { puts 'fiber!' }
#=> #<Fiber:0x007f9175d7d210>
Fiber.ancestors
# => [Fiber, Object, Kernel, BasicObject]
Fiber.instance_methods(false)
#=> [:resume]
f.resume
# => fiber!
# transferを使わない
f1 = Fiber.new { 'one' }
f2 = Fiber.new { f1.resume; 'two' }
puts f2.resume #=> two
# f1もf2も既に死んでいる
puts f1.resume #=> dead fiber called (FiberError)
puts f2.resume #=> dead fiber called (FiberError)
pr = Proc.new { puts 'proc!' }
pr.call # => proc!
f = Fiber.new do
Fiber.yield 'return by yield' # 処理を親に戻す
Fiber.yield 'return by yield again'
'end of block'
end
puts '--- 1 ---'
f.resume #=> 'return by yield'
puts '--- 2 ---'
f.resume #=> 'return by yield again'
puts '--- 3 ---'
f.resume #=> 'end of block'
puts '--- 4 ---'
f.resume #=> FiberError: dead fiber called
# transferを使う
require 'fiber'
f1 = Fiber.new { 'one' }
f2 = Fiber.new { f1.transfer; 'two' }
puts f2.resume #=> one
# 一度transferしたfiberはresumeできない
puts f1.resume #=> cannot resume transferred Fiber (FiberError)
puts f2.resume #=> double resume (FiberError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment