Created
February 11, 2013 13:32
-
-
Save mdaisuke/4754431 to your computer and use it in GitHub Desktop.
thread safety
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 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