Skip to content

Instantly share code, notes, and snippets.

@chuckremes
Last active December 30, 2017 10:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chuckremes/14c9ef06efc0bc62b9dc5b588c06719f to your computer and use it in GitHub Desktop.
Save chuckremes/14c9ef06efc0bc62b9dc5b588c06719f to your computer and use it in GitHub Desktop.
require 'fiber'
Thread.abort_on_exception = true
class Foo
def initialize(a_val)
puts "Step 1"
@io_fiber = Fiber.new do |calling_fiber|
puts "Step 4"
some_val = calling_fiber.transfer(a_val)
puts "Step 7"
2
end
puts "Step 2"
end
def complete_setup
# calls into block above, so Fiber.current becomes +calling_fiber+
puts "Step 3"
value = @io_fiber.transfer(Fiber.current)
puts "Step 5"
value
end
def enqueue(b_val)
puts "Step 6"
value = @io_fiber.transfer(b_val)
puts "Step 8"
value
end
end
f1 = Foo.new(16)
puts f1.complete_setup # should output 16
puts f1.enqueue(18) # should output 2
t2 = Thread.new do
puts "Starting steps over from new thread, using new Foo object and fibers"
f2 = Foo.new(25)
puts f2.complete_setup # should output 25
puts f2.enqueue(33) # should output 2
end
sleep 2
Charless-Air:ruby-io cremes$ ruby -v
jruby 9.1.15.0 (2.3.3) 2017-12-07 929fde8 Java HotSpot(TM) 64-Bit Server VM 25.144-b01 on 1.8.0_144-b01 +jit [darwin-x86_64]
Charless-Air:ruby-io cremes$ ruby g.rb
Step 1
Step 2
Step 3
Step 4
FiberError: fiber called across threads
__transfer__ at org/jruby/ext/fiber/ThreadFiber.java:186
block in initialize at g.rb:9
cremes$ ruby -v
ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-darwin16]
Charless-Air:ruby-io cremes$ ruby g.rb
Step 1
Step 2
Step 3
Step 4
Step 5
16
Step 6
Step 7
Step 8
2
Starting steps over from new thread, using new Foo object and fibers
Step 1
Step 2
Step 3
Step 4
Step 5
25
Step 6
Step 7
Step 8
2
Charless-Air:ruby-io cremes$ ruby -v
rubinius 3.86.c109 (2.3.1 65a8656f 2017-12-29 5.0.0) [x86_64-darwin16.7.0]
cremes$ ruby g.rb
Step 1
Step 2
Step 3
Step 4
Step 5
16
Step 6
Step 7
Step 8
2
Starting steps over from new thread, using new Foo object and fibers
Step 1
Step 2
Step 3
Step 4
call # Proc at core/proc.rb:20
{ } in initialize # Foo at g.rb:9
attempt to transfer fiber across threads: current thread: 6, objid: 0, Fiber Thread: 1, objid: 0, Fiber objid: 0 (FiberError)
An exception occurred running g.rb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment