Last active
March 1, 2016 16:17
-
-
Save anildigital/b9441df00eb7870289f0 to your computer and use it in GitHub Desktop.
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
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