Created
May 14, 2013 01:14
-
-
Save havenwood/5572888 to your computer and use it in GitHub Desktop.
Producer-consumer problem in Ruby with SizedQueue
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
require 'thread' | |
class ProducerConsumer | |
def initialize producers = 5, consumers = 5, queue_size = 5 | |
@producers, @consumers = producers, consumers | |
@queue = SizedQueue.new queue_size | |
@mutex = Mutex.new | |
@threads = [] | |
end | |
def run | |
producers | |
consumers | |
end | |
def producers | |
@producers.times do | |
@threads << Thread.new do | |
loop do | |
@queue << 'a widget' | |
say "Produced a widget: #{@queue.size} in queue..." | |
end | |
end | |
end | |
end | |
def consumers | |
@consumers.times do | |
@threads << Thread.new do | |
loop do | |
@queue.pop | |
say "Consumed a widget: #{@queue.size} in queue..." | |
end | |
end | |
end | |
end | |
def say this | |
@mutex.synchronize do | |
puts this | |
end | |
end | |
def kill | |
@threads.each &:kill | |
end | |
end | |
pc = ProducerConsumer.new | |
pc.run | |
sleep 0.5 | |
pc.kill |
lol, im just gonna assume that was a joke
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What kind of problem did you experienced? Is it because access to the queue wasn't properly synchronized between threads?