Skip to content

Instantly share code, notes, and snippets.

@vessi
Last active January 1, 2016 08:19
Show Gist options
  • Save vessi/8117079 to your computer and use it in GitHub Desktop.
Save vessi/8117079 to your computer and use it in GitHub Desktop.
require 'thread'
MAX_THREADS = 5
class BlockingQueue
def initialize
@mutex = Mutex.new
@got_one = ConditionVariable.new
@store = []
end
def push(val)
@mutex.synchronize do
@store.push(val)
@got_one.signal
end
end
def pop
@mutex.synchronize do
@got_one.wait(@mutex) if @store.empty?
@store.pop
end
end
end
@queue = BlockingQueue.new
MAX_THREADS.times.map do |name|
Thread.new do
sleep(rand(10))
@queue.push(Time.now.to_s + ' ' + name.to_s)
end
end
collected = 0
until collected >= MAX_THREADS do
puts @queue.pop.inspect
collected += 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment