Created
June 15, 2018 15:18
-
-
Save havenwood/136aca0d7b01296f03c63bc464c4924e to your computer and use it in GitHub Desktop.
Three Fibers Dancing in a Clock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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