Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created May 14, 2013 01:14
Show Gist options
  • Save havenwood/5572888 to your computer and use it in GitHub Desktop.
Save havenwood/5572888 to your computer and use it in GitHub Desktop.
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
@deeTEEcee
Copy link

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