Skip to content

Instantly share code, notes, and snippets.

@squarism
Last active December 19, 2015 18:18
Show Gist options
  • Save squarism/5997096 to your computer and use it in GitHub Desktop.
Save squarism/5997096 to your computer and use it in GitHub Desktop.
Here's an example you can play with from José Valim's talk on concurrency. Set num_threads to anything above 1. Use jruby for maximum thread conflict chance.
# run me with jruby so that race conditions happen more frequently
# run with num_threads = 1 and then change num_threads to anything above 1.
# notice the difference? :D
num_threads = 1
require 'active_support'
class Counter
cattr_accessor :i
self.i = 0
def self.count_up
self.i = self.i + 1
end
end
count_to = 1000
iterations = 0
num_threads.times.map do
Thread.new {
while iterations < count_to
Counter.i = Counter.i + 1
iterations += 1
end
}
end.each(&:join)
puts Counter.i
raise "Race condition foo!" if Counter.i != count_to
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment