Skip to content

Instantly share code, notes, and snippets.

@vigneshwaranr
Created August 22, 2015 14:47
Show Gist options
  • Save vigneshwaranr/83e21b37d54fc230a875 to your computer and use it in GitHub Desktop.
Save vigneshwaranr/83e21b37d54fc230a875 to your computer and use it in GitHub Desktop.
This Class is just my exercise to try ConditionVariable in Ruby
require 'thread'
#This Class is just my exercise to try ConditionVariable
class BlockingQueue
def initialize
@queue = Queue.new
@semaphore = Mutex.new
@condition = ConditionVariable.new
end
def put element
@queue << element
@semaphore.synchronize do
puts 'putting and notifying for ' + element.to_s
@condition.signal
end
end
def take
while @queue.empty? do
@semaphore.synchronize do
puts 'Waiting on take..'
@condition.wait(@semaphore)
end
end
i = @queue.pop
puts 'Taken ' + i.to_s
i
end
end
#Testing the above class
Thread.abort_on_exception = true
t = []
lbq = BlockingQueue.new
1.times {
t << Thread.new {
loop do
lbq.take
end
}
}
2.times {
t << Thread.new {
loop do
lbq.put rand 100
sleep 2
end
}
}
t.each {|thr| thr.join }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment