Created
January 22, 2014 21:33
-
-
Save laser/8567773 to your computer and use it in GitHub Desktop.
Multithread safe
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
def add_range_safe | |
threads = (1..256).each_slice(16).map do |range| | |
Thread.new do | |
Thread.current[:sum] = range.inject(0) do |memo, n| | |
StatelessCalculator.add memo, n | |
end | |
end | |
end | |
result = threads.map { |t| t.join[:sum] } .reduce(:+) | |
end | |
puts add_range_safe # 32896 | |
puts add_range_safe # 32896 | |
puts add_range_safe # 32896 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment