Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'nio'
require 'fiber'
require 'timers'
require 'io/nonblock'
class Scheduler
def initialize
@selector = NIO::Selector.new
@fibers = {}
@timers = Timers::Group.new
end
def io_wait(io, _events, timeout)
@selector.register io, :rw
@fibers[io] = Fiber.current
if timeout
@timers.after(timeout) do
fibers[:io].resume
end
end
Fiber.yield
end
def run
until @fibers.empty?
@selector.select(interval) do |m|
fiber = @fibers.delete(m.io)
@selector.deregister m.io
fiber.resume
end
end
end
def interval
@timers.wait_interval
end
def close
run
end
def fiber(&block)
fiber = Fiber.new(blocking: false, &block)
fiber.resume
fiber
end
end
Thread.current.scheduler = Scheduler.new
i, o = UNIXSocket.pair
Fiber.schedule do
message = i.read(20)
i.close
puts message
end
Fiber.schedule do
o.write('Hello World')
o.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment