Created
May 20, 2014 15:14
-
-
Save jvranish/ab727bb99d9357cc28c1 to your computer and use it in GitHub Desktop.
Ruby pop with timeout implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Technically this is a stack with timeout (since you use
@queue.pop
rather than@queue.shift
on L26.)