Skip to content

Instantly share code, notes, and snippets.

@mdaisuke
Created February 11, 2013 13:32
Show Gist options
  • Save mdaisuke/4754431 to your computer and use it in GitHub Desktop.
Save mdaisuke/4754431 to your computer and use it in GitHub Desktop.
thread safety
class Inventory
def initialize(stock_levels)
@stock = stock_levels
end
def decrease(item)
@stock[item] -= 1
end
def [](item)
@stock[item]
end
end
#4000.times do
# inventory.decrease(:hats)
#end
#
#puts inventory[:hats]
inventory = Inventory.new(:hats => 4000)
threads = Array.new
40.times do
threads << Thread.new do
100.times do
inventory.decrease(:hats)
end
end
end
threads.each(&:join)
puts inventory[:hats]
inventory = Inventory.new(:hats => 4000)
threads = Array.new
lock = Mutex.new
400.times do
threads << Thread.new do
lock.synchronize do
10.times do
inventory.decrease(:hats)
end
end
end
end
threads.each(&:join)
puts inventory[:hats]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment