Skip to content

Instantly share code, notes, and snippets.

@jvranish
Created May 20, 2014 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvranish/ab727bb99d9357cc28c1 to your computer and use it in GitHub Desktop.
Save jvranish/ab727bb99d9357cc28c1 to your computer and use it in GitHub Desktop.
Ruby pop with timeout implementation
class QueueWithTimeout
def initialize
@mutex = Mutex.new
@queue = []
@recieved = ConditionVariable.new
end
def <<(x)
@mutex.synchronize do
@queue << x
@recieved.signal
end
end
def pop(non_block = false)
pop_with_timeout(non_block ? 0 : nil)
end
def pop_with_timeout(timeout = nil)
@mutex.synchronize do
if @queue.empty?
@recieved.wait(@mutex, timeout) if timeout != 0
#if we're still empty after the timeout, raise exception
raise ThreadError, "queue empty" if @queue.empty?
end
@queue.pop
end
end
end
@nornagon
Copy link

Technically this is a stack with timeout (since you use @queue.pop rather than @queue.shift on L26.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment