/threadsafe_array.rb Secret
Last active
March 11, 2016 19:01
-
-
Save havenwood/9c54c8991c3469a3f82e to your computer and use it in GitHub Desktop.
threadsafe?
This file contains 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
#!/usr/bin/env ruby | |
class Foo | |
def initialize level | |
@level = level | |
end | |
def decrease it | |
@level[it] -= 1 | |
end | |
def [] it | |
@level[it] | |
end | |
end | |
foo = Foo.new a: 1000, b: 200, c: 300 | |
print 'Before: ' | |
p foo | |
threads = [] | |
100.times do | |
threads << Thread.new do | |
10.times do | |
foo.decrease :a | |
end | |
puts "#{foo[:a]}\n" | |
end | |
end | |
threads.each &:join | |
print 'After: ' | |
p foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment