To get a better understanding of pessimist locking (with InnoDB), I tried to run this code in my Rails application:
Thread.new do
Account.transaction do
account = Account.lock(true).first
account.balance += 250
account.save!
end
end
Thread.new do
Account.transaction do
account = Account.lock(true).first
account.balance += 500
account.save!
end
end
It actually works, account.balance
then contains 750
, then 1500
on the next hit. Without locking, it just takes the last thread into consideration and the result is 500
.
Is that a dumb test to try out the difference between locking or not? I think I understand the principle of pessimist locking, but not sure though.