问题
I'm currently using Mysql with InnoDB storage engine for all tables.
So, I'm wondering if this is a real problem and if there's a solution for it.
For example, I will charge a user using a database transaction: 1. check his balance 2. subtract his balance 3. credit this balance somewhere 4. commit
What would happen if an update happens just after #1 and before 2 & 3. If the user withdraws or purchases something else that results his balance to be zero. This would have led to to lose that balance. From what I understand, step #1 would only cause a shared lock and would not block writes, etc.
Is there a common solution for this?
回答1:
Your tags suggest that you understand what the answer is -- locking. Relational databases (generally) implement the ACID properties of transactions, which ensure consistency of data. In practice, these are sometimes relaxed for performance reasons, but most databases offer some method to achieve this goal.
In MySQL, the locking mechanisms depend on the underlying storage engine. InnoDB offers several options, which are described in the documentation.
To achieve these locks, you basically have two syntactic options with a SELECT
:
select . . . for update
select . . . lock in share mode
Note that these statements should be used in an explicit transaction.
来源:https://stackoverflow.com/questions/32796684/locking-and-concurrency-with-mysql