Skip to content

Instantly share code, notes, and snippets.

@ploubser
Last active December 10, 2015 23:39
Show Gist options
  • Save ploubser/4511307 to your computer and use it in GitHub Desktop.
Save ploubser/4511307 to your computer and use it in GitHub Desktop.
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