Sha256: 76635b734f308ef9d650f1d8c4e3f9ae22dbb39ad4193fe71305c786027561f8
Contents?: true
Size: 1.56 KB
Versions: 1
Compression:
Stored size: 1.56 KB
Contents
java_import java.lang.System module ZMachine class HashedWheelTimeout attr_reader :deadline attr_reader :callback def initialize(deadline, &block) @deadline = deadline @callback = block @canceled = false end def cancel @canceled = true end def canceled? @canceled end end class HashedWheel attr_reader :slots attr_accessor :last def initialize(number_of_slots, tick_length, start_time = System.nano_time) @slots = Array.new(number_of_slots) { [] } @tick_length = tick_length * 1_000_000_000 @last = start_time @current_tick = 0 end def add(timeout, &block) timeout *= 1_000_000_000 # s to ns ticks = timeout / @tick_length slot = (@current_tick + ticks) % @slots.length deadline = System.nano_time + timeout @slots[slot] << hwt = HashedWheelTimeout.new(deadline, &block) hwt end def reset(time = nil) @slots = Array.new(@slots.length) { [] } @current_tick = 0 @last = time || System.nano_time end # returns all timeouts def advance(now = nil) now ||= System.nano_time passed_ticks = (now - @last) / @tick_length result = [] begin @current_tick %= @slots.length @slots[@current_tick].delete_if do |timeout| result << timeout if timeout.deadline < now end @current_tick += 1 passed_ticks -= 1 end while passed_ticks > 0 @last = now result.reject do |timeout| timeout.canceled? end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
zmachine-0.3.2 | lib/zmachine/hashed_wheel.rb |