Last active
December 10, 2015 23:39
-
-
Save ploubser/4511307 to your computer and use it in GitHub Desktop.
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 ThreadsafeQueue | |
require 'thread' | |
require 'timeout' | |
def initialize | |
@queue = [] | |
@mutex = Mutex.new | |
@cv = ConditionVariable.new | |
end | |
def push(item) | |
@mutex.synchronize do | |
@queue.push(item) | |
end | |
@cv.signal | |
end | |
alias_method :<<, :push | |
def pop | |
@mutex.synchronize do | |
while true | |
if @queue.empty? | |
begin | |
Timeout::timeout(5) do | |
@cv.wait(@mutex) | |
end | |
rescue Timeout::Error | |
retry | |
end | |
else | |
return @queue.shift | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment