如何实现“先读后写锁"在 MySQL 中? [英] How to impliment a "read then write lock" in MySQL?

查看:33
本文介绍了如何实现“先读后写锁"在 MySQL 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 MySQL 数据库的 PHP 应用程序.我想防止两个请求执行相同(重复)的操作.

我想在记录上设置一个字段,以便第一个请求可以将其设置为 true 并让其他请求知道它当前正在处理".

if ($currentlyBeingProcessed) {//离开这里} 别的 {//锁定要处理的行}

我意识到我可能会遇到这样一种情况,即两个请求在时间上非常接近,以至于在第一个请求可以写入当前正在处理"的数据库之前,它们都可以读取该记录未处理"".

在 MySQL 中有没有办法锁定其他请求读取它的行,直到第一个请求成功完成写入数据库?我将如何做到这一点?

解决方案

SELECT ... FOR UPDATE 可能正是您要找的.

I have a PHP application using a MySQL database. I would like to prevent two requests from performing the same (duplicate) action.

I would like to set a field on the record so that the first request can set it to true and let the other requests know that it is "currently being processed".

if ($currentlyBeingProcessed) {
    //get out of here
} else {
    //lock the row for processing
}

I realized that I could get into a situation where the two requests are so close in time that they could both read that record is "not being processed" before the first request could write to the database that it is "currently being processed".

Is there a way in MySQL to lock the row from other requests reading it until the first request has successfully finished writing to the database? How would I accomplish this?

解决方案

SELECT ... FOR UPDATE might be what you're looking for.

这篇关于如何实现“先读后写锁"在 MySQL 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆