Skip to content

Instantly share code, notes, and snippets.

@anildigital
Last active March 1, 2016 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anildigital/b9441df00eb7870289f0 to your computer and use it in GitHub Desktop.
Save anildigital/b9441df00eb7870289f0 to your computer and use it in GitHub Desktop.
BUFFER_SIZE = 100
semaphore = Mutex.new
require 'thread'
queue = Thread::Queue.new
class Item
attr_reader :data
def initialize
@data = (0...8).map { (65 + rand(26)).chr }.join
end
def to_s
@data
end
end
def consume_item(item)
puts "Thread Consumed #{item}"
end
def produce_item
item = Item.new
puts "Thread Produced #{item}"
item
end
# Producer
producers = []
(1..100).each do |i|
producers << Thread.new("producer_#{i}") do
while true
semaphore.synchronize {
item = produce_item
if queue.size < BUFFER_SIZE
queue << item
end
puts "In producer #{queue.size}"
}
end
end
end
# Consumer
consumers = []
(1..100).each do |i|
consumers << Thread.new("consumer_#{i}") do
while true
semaphore.synchronize {
if queue.size > 0
consume_item(queue.pop)
end
}
end
end
end
[producers, consumers].flatten.each { |thr| thr.join }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment