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