mysql insert race condition

后端 未结 8 1468
暗喜
暗喜 2020-12-09 06:19

How do you stop race conditions in MySQL? the problem at hand is caused by a simple algorithm:

  1. select a row from table
  2. if it doesn\'t exist, insert it
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 06:31

    On a technical level, a transaction will help here because other threads won't see the new row until you commit the transaction.

    But in practice that doesn't solve the problem - it only moves it. Your application now needs to check whether the commit fails and decide what to do. I would normally have it rollback what you did, and restart the transaction because now the row will be visible. This is how transaction-based programmer is supposed to work.

提交回复
热议问题