Locking and concurrency with MySQL

扶醉桌前 提交于 2021-02-05 07:27:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!