Skip to content

Instantly share code, notes, and snippets.

@carld
Created April 19, 2022 23:36
Show Gist options
  • Save carld/7fa923ced6ca6abf08c993d5a6c75873 to your computer and use it in GitHub Desktop.
Save carld/7fa923ced6ca6abf08c993d5a6c75873 to your computer and use it in GitHub Desktop.
Ruby Fibres example
class Engine
def initialize
@tick = 0
@event_count = 0
@queue = []
@fibre = Fiber.new do |arg|
loop do
@tick += 1
e = @queue.pop
break if e == :stop
@event_count += 1 if e
puts "#{@tick} #{@event_count} event: #{e}"
Fiber.yield
end
end
end
def start
@fibre.resume
end
def continue
@fibre.resume
end
def stop
@queue.unshift(:stop)
end
def event
@queue.unshift(:event)
end
end
e = Engine.new
e.start # 1 0
e.event
e.continue # 2 1 event
e.event
e.continue # 3 2 event
e.continue # 4 2
e.continue # 5 2
e.stop
e.continue
e.continue # error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment