Skip to content

Instantly share code, notes, and snippets.

@mikbe
Created June 17, 2011 12:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mikbe/1031308 to your computer and use it in GitHub Desktop.
Verify thread collisions are possible
require 'thread'
class Foo
attr_accessor :bar
def baz
@bar ||= rand(10000000000)
end
end
f = Foo.new
baz1 = -1
baz2 = -1
count = 0
last_one = ""
while baz1 == baz2
last_one = "f.bar: #{f.bar}; baz1: #{baz1}; baz2: #{baz2}"
f.bar = nil
wait_til = Time.now + 0.01
Thread.new {sleep (wait_til - Time.now); baz1 = f.baz }
Thread.new {sleep (wait_til - Time.now); baz2 = f.baz }
sleep 0.02
count += 1
if count == 100
puts "working: #{last_one}"
count = 0
end
end
puts
puts "Thread collision"
puts "previous: #{last_one}" # Just to prove it's not remembering value from last iteration but is a real collision
puts "current: f.bar: #{f.bar}; baz1: #{baz1}; baz2: #{baz2}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment