Skip to content

Instantly share code, notes, and snippets.

@metanest
Created December 12, 2015 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metanest/c7bbf960e5d7a0cf963d to your computer and use it in GitHub Desktop.
Save metanest/c7bbf960e5d7a0cf963d to your computer and use it in GitHub Desktop.
#! /usr/local/bin/ruby22
require 'fiber'
N = 1000000
class PingPong
def initialize
@ping_fiber = Fiber.new {
count = 0
while count < N do
@pong_fiber.transfer
count += 1
end
}
@pong_fiber = Fiber.new {
count = 0
while count < N do
@ping_fiber.transfer
count += 1
end
}
end
def run
@ping_fiber.resume
end
end
ping_pong = PingPong.new
ping_pong.run
#! /usr/local/bin/ruby22
N = 1000000
class PingPong
def initialize
q1 = Queue.new
q2 = Queue.new
@ping_thread = Thread.new {
count = 0
while count < N do
q1.enq nil
q2.deq
count += 1
end
q1.enq nil
}
@pong_thread = Thread.new {
q1.deq
count = 0
while count < N do
q2.enq nil
q1.deq
count += 1
end
}
end
def join
@ping_thread.join
@pong_thread.join
end
end
ping_pong = PingPong.new
ping_pong.join
#! /usr/local/bin/ruby22
N = 1000000
class PingPong
def initialize
@ping_thread = Thread.new {
Thread.stop
count = 0
while count < N do
@pong_thread.wakeup
Thread.stop
count += 1
end
@pong_thread.wakeup
}
@pong_thread = Thread.new {
@ping_thread.wakeup
Thread.stop
count = 0
while count < N do
@ping_thread.wakeup
Thread.stop
count += 1
end
}
end
def join
@ping_thread.join
@pong_thread.join
end
end
ping_pong = PingPong.new
ping_pong.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment