Object
Replaces timeout.rb to avoid Thread creation and scheduling overhead.
You should check another timeout replace in WEBrick. See lib/webrick/utils.rb in ruby/1.9.
About this implementation:
Do not create Thread for each timeout() call. Just create 1 Thread for timeout scheduler.
Do not wakeup the scheduler thread so often. Let scheduler thread sleep until the nearest period.
Creates new TimeoutScheduler.
# File lib/httpclient/timeout.rb, line 56 56: def initialize 57: @pool = {} 58: @next = nil 59: @thread = start_timer_thread 60: end
Cancels the given period.
# File lib/httpclient/timeout.rb, line 78 78: def cancel(period) 79: @pool.delete(period) 80: period.cancel 81: end
Registers new timeout period.
# File lib/httpclient/timeout.rb, line 63 63: def register(thread, sec, ex) 64: period = Period.new(thread, Time.now + sec, ex || ::Timeout::Error) 65: @pool[period] = true 66: if @next.nil? or period.time < @next 67: begin 68: @thread.wakeup 69: rescue ThreadError 70: # Thread may be dead by fork. 71: @thread = start_timer_thread 72: end 73: end 74: period 75: end
# File lib/httpclient/timeout.rb, line 85 85: def start_timer_thread 86: thread = Thread.new { 87: while true 88: if @pool.empty? 89: @next = nil 90: sleep 91: else 92: min, = @pool.min { |a, b| a[0].time <=> b[0].time } 93: @next = min.time 94: sec = @next - Time.now 95: if sec > 0 96: sleep(sec) 97: end 98: end 99: now = Time.now 100: @pool.keys.each do |period| 101: if period.time < now 102: period.raise('execution expired') 103: cancel(period) 104: end 105: end 106: end 107: } 108: Thread.pass while thread.status != 'sleep' 109: thread 110: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.