Skip to content

Instantly share code, notes, and snippets.

@NonLogicalDev
Last active December 20, 2015 23:28
Show Gist options
  • Save NonLogicalDev/6212283 to your computer and use it in GitHub Desktop.
Save NonLogicalDev/6212283 to your computer and use it in GitHub Desktop.
class EventLoop
class AlreadyRunning < StandardError; end
class CantTerminate < StandardError; end
def start
raise AlreadyRunning, "Event loop is already running" if @event_loop
@event_loop = Thread.new do
Thread.current[:events] = []
loop do
sleep
Thread.current[:events].each do |event|
puts "Received event #{event[:category]}"
event[:callback].call()
end
end
end
end
def stop
@event_loop.exit
if @event_loop.status == 'aborting' || @event_loop.status == 'dead'
@event_loop = nil
else
raise CantTerminate, "Cant terminate event loop"
end
end
def queue_event(category, &callback)
@event_loop[:events].push(category: category, callback: callback)
@event_loop.wakeup
end
def self.generate_event(categoryi, &callback)
{ category: category, callback: callback }
end
end
machine = EventLoop.new()
machine.start()
machine.queue_event("test") do
puts "Lol"
end
sleep(2)
machine.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment