Concurrency and Modules
Mutex Inventory
A mutex keeps shared state updates consistent when more than one thread changes the same object.
Mutex Inventory
mutex_inventory.rb
orders_per_worker =
stock = { "book" => 10 }
lock = Mutex.new
workers = 2.times.map do
Thread.new do
orders_per_worker.times do
lock.synchronize do
current = stock["book"]
stock["book"] = current - 1
end
end
end
end
workers.each(&:join)
sold = 10 - stock["book"]
puts "orders_per_worker=#{orders_per_worker}"
puts "sold=#{sold}"
puts "remaining=#{stock["book"]}"
orders_per_worker =
stock = { "book" => 10 }
lock = Mutex.new
workers = 2.times.map do
Thread.new do
orders_per_worker.times do
lock.synchronize do
current = stock["book"]
stock["book"] = current - 1
end
end
end
end
workers.each(&:join)
sold = 10 - stock["book"]
puts "orders_per_worker=#{orders_per_worker}"
puts "sold=#{sold}"
puts "remaining=#{stock["book"]}"
orders_per_worker =
stock = { "book" => 10 }
lock = Mutex.new
workers = 2.times.map do
Thread.new do
orders_per_worker.times do
lock.synchronize do
current = stock["book"]
stock["book"] = current - 1
end
end
end
end
workers.each(&:join)
sold = 10 - stock["book"]
puts "orders_per_worker=#{orders_per_worker}"
puts "sold=#{sold}"
puts "remaining=#{stock["book"]}"
mutex updates
Wrap the read-modify-write section with `synchronize` so one thread updates the inventory at a time.