Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Producer-consumer problem in Ruby with SizedQueue
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
@zekefast

This comment has been minimized.

Copy link

@zekefast zekefast commented Jun 19, 2015

What kind of problem did you experienced? Is it because access to the queue wasn't properly synchronized between threads?

@deeTEEcee

This comment has been minimized.

Copy link

@deeTEEcee deeTEEcee commented May 8, 2017

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
You can’t perform that action at this time.