Skip to content

Instantly share code, notes, and snippets.

@rocky-jaiswal
Created June 24, 2013 04:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rocky-jaiswal/5847810 to your computer and use it in GitHub Desktop.
Save rocky-jaiswal/5847810 to your computer and use it in GitHub Desktop.
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