Created
June 24, 2013 04:54
-
-
Save rocky-jaiswal/5847810 to your computer and use it in GitHub Desktop.
Producer Consumer problem with locks
This file contains hidden or 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
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