Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A demonstration of transfer of control to/from a Fiber in Ruby 1.9.x.
fib = Fiber.new do |val|
puts ' -- 2 --'
puts 'fiber started & got: ' + val
puts 'now yield with "1st yield"'
val = Fiber.yield('fiber yield 1')
puts ' -- 4 --'
puts '1st yield got: ' + val
puts 'now yield with "2nd yield"'
val = Fiber.yield('fiber yield 2')
puts ' -- 6 --'
puts '2nd yield got: ' + val
puts 'now return "fiber return"'
'fiber return'
end
puts ' -- 1 --'
puts 'now resume with "resume 1"'
val = fib.resume('resume 1')
puts ' -- 3 --'
puts '1st resume got: ' + val
puts 'now resume with "resume 2"'
val = fib.resume('resume 2')
puts ' -- 5 --'
puts '2nd resume got: ' + val
puts 'now resume with "resume 3"'
val = fib.resume('resume 3')
puts ' -- 7 --'
puts '3rd resume got: ' + val
puts 'now return after fiber has finished'
fib.resume
# Running this code results in ...
#
# -- 1 --
# now resume with "resume 1"
# -- 2 --
# fiber started & got: resume 1
# now yield with "1st yield"
# -- 3 --
# 1st resume got: fiber yield 1
# now resume with "resume 2"
# -- 4 --
# 1st yield got: resume 2
# now yield with "2nd yield"
# -- 5 --
# 2nd resume got: fiber yield 2
# now resume with "resume 3"
# -- 6 --
# 2nd yield got: resume 3
# now return "fiber return"
# -- 7 --
# 3rd resume got: fiber return
# now return after fiber has finished
# fiber_demo.rb:42:in `resume': dead fiber called (FiberError)
# from fiber_demo.rb:42:in `<main>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.