Skip to content

Instantly share code, notes, and snippets.

@spalenza
Created March 21, 2019 13:10
Show Gist options
  • Save spalenza/568d375d6b697a4365d8930cc0df6459 to your computer and use it in GitHub Desktop.
Save spalenza/568d375d6b697a4365d8930cc0df6459 to your computer and use it in GitHub Desktop.
Rails Race Condition - Pessimistic Locking
def update(i)
ActiveRecord::Base.transaction do
sleep(0.5)
id = 5928598
person = Person.lock.find(id)
person.name = "Rodolfo#{i}"
person.save!
end
end
threads = []
ActiveRecord::Base.transaction do
id = 5928598
person = Person.lock.find(id)
10.times do |i|
threads << Thread.new { update(i) }
end
sleep(5)
person.name = "Rodolfo"
person.save!
end
threads.each(&:join)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment