数据库
首页 > 数据库> > MySQL:防止竞争条件 – 更新或锁定共享模式?

MySQL:防止竞争条件 – 更新或锁定共享模式?

作者:互联网

这是我想要的交易订单:

> User1选择字段,执行操作,使用新值更新.
> User2选择字段,执行操作,使用新值更新.
> User3选择字段,执行操作,使用新值更新.

从我understand开始,第一个选择仅执行写锁定,而第二个选择执行读写锁定.

两者似乎都可用,但在第一种情况下,User2读取的值是多少? User1更新前的初始值,或者User1更新后的值(这是我想要的)?

所以我很困惑,我应该使用SELECT … FOR UPDATE或SELECT … LOCK IN SHARE MODE?

解决方法:

您可能想要使用FOR UPDATE.

使用“LOCK IN SHARE MODE”,第二个用户仍然可以在更新之前读取该值.

来自MySQL文档:

If you use FOR UPDATE with a storage
engine that uses page or row locks,
rows examined by the query are
write-locked until the end of the
current transaction. Using LOCK IN
SHARE MODE sets a shared lock that
allows other transactions to read the
examined rows but not to update or
delete them.

因此,即使LOCK IN SHARE MODE阻止更新,如果操作取决于读取值,您可能最终处于不一致状态.

标签:mysql,race-condition
来源: https://codeday.me/bug/20190827/1743512.html