class Async::Task
def self.current
def self.current Thread.current[:async_task] or raise RuntimeError, "No async task available!" end
def bind(io)
def bind(io) @ios[io.fileno] ||= reactor.wrap(io, self) end
def close
def close @ios.each_value(&:close) end
def initialize(ios, reactor, &block)
def initialize(ios, reactor, &block) @ios = Hash[ ios.collect{|io| [io.fileno, reactor.wrap(io, self)]} ] @reactor = reactor @fiber = Fiber.new do set! begin yield(*@ios.values, self) # Async.logger.debug("Task #{self} completed normally.") rescue Interrupt # Async.logger.debug("Task #{self} interrupted: #{$!}") ensure close end end end
def register(io, interests)
def register(io, interests) @reactor.register(io, interests) end
def run
def run @fiber.resume return @fiber end
def set!
def set! # This is actually fiber-local: Thread.current[:async_task] = self end
def stop!
def stop! if @fiber.alive? exception = Interrupt.new("Stop right now!") @fiber.resume(exception) end end
def with(io)
def with(io) wrapper = @reactor.wrap(io, self) yield wrapper ensure wrapper.close io.close end