Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created June 15, 2018 15:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/136aca0d7b01296f03c63bc464c4924e to your computer and use it in GitHub Desktop.
Save havenwood/136aca0d7b01296f03c63bc464c4924e to your computer and use it in GitHub Desktop.
Three Fibers Dancing in a Clock
require 'fiber'
module Clock
DEFAULT_SECONDS = 4
module_function
def run seconds: DEFAULT_SECONDS
timer.resume tick, tock, seconds: seconds
end
alias call run
def timer
Fiber.new do |ticker, tocker, seconds: DEFAULT_SECONDS|
beats = [ticker, tocker].cycle
seconds.times do
sleep 1
beats.next.transfer Fiber.current
end
'en fin'
end
end
def tick
Fiber.new do |time|
loop do
puts 'tick'
time.transfer
end
end
end
def tock
Fiber.new do |time|
loop do
puts 'tock'
time.transfer
end
end
end
end
2.times.map { Thread.new { Clock.run } }.map &:value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment