Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Producer Consumer problem with locks
class Cook
def produce
"item"
end
end
class Consumer
def consume(item)
#do something with item
end
end
class Executor
MAX_ITEMS = 10
def self.execute
items = []
semaphore = Mutex.new
pt = Thread.new do
producer = Cook.new
while true do
semaphore.synchronize {
if items.size < MAX_ITEMS
items.push producer.produce
puts Thread.current.to_s + " Produced item ... Stock : " + items.size.to_s
end
}
sleep 2
end
end
ct = Thread.new do
consumer = Consumer.new
while true do
semaphore.synchronize {
if items.size > 0
consumer.consume items.pop
puts Thread.current.to_s + " Consumed item ... Stock : " + items.size.to_s
end
}
sleep 2
end
end
pt.join
ct.join
end
end
Executor.execute
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.