1
0
Fork 0
mirror of https://github.com/mperham/connection_pool synced 2023-03-27 23:22:21 -04:00
connection_pool/lib/timed_queue.rb

43 lines
744 B
Ruby
Raw Normal View History

require 'thread'
require 'timeout'
class TimedQueue
2012-03-14 09:21:07 -04:00
def initialize(size = 0)
@que = Array.new(size) { yield }
@mutex = Mutex.new
@resource = ConditionVariable.new
end
def push(obj)
@mutex.synchronize do
@que.push obj
@resource.broadcast
end
end
2011-05-14 22:42:07 -04:00
alias_method :<<, :push
def timed_pop(timeout=0.5)
deadline = Time.now + timeout
2011-05-14 22:42:07 -04:00
@mutex.synchronize do
loop do
return @que.shift unless @que.empty?
to_wait = deadline - Time.now
2011-09-19 17:27:20 -04:00
raise Timeout::Error, "Waited #{timeout} sec" if to_wait <= 0
@resource.wait(@mutex, to_wait)
end
end
end
def empty?
@que.empty?
end
def clear
@que.clear
end
def length
@que.length
end
end