dongqin1861 2014-07-16 21:20
浏览 550
已采纳

MySQL使并发SELECT ... FOR UPDATE查询失败,而不是等待释放锁

In my PHP code I'm trying to make an innoDB database transaction be ignored if another thread is already performing the transaction on the row. Here's some code as an example:

$db = connect_db();
try{
    $db->beginTransaction();
    $query = "SELECT val FROM numbers WHERE id=1 FOR UPDATE"; //I want this to throw an exception if row is already selected for update
    make_query($db,$query); //function I use to make queries with PDO

    sleep(5); //Added to delay the transaction
    $num = rand(1,100);

    $query = "UPDATE numbers SET val='$num' WHERE id=1";
    make_query($db,$query);
    $db->commit();
    echo $num;
}
catch (PDOException $e){
    echo $e;
}

When it makes the SELECT val FROM numbers WHERE id=1 FOR UPDATE query I need some way of knowing through php if the thread is waiting for another thread to finish it's transaction and release the lock. What ends up happening is the first thread finishes the transaction and the second thread overwrites its changes immediately afterwards. Instead I want the first transaction to finish and the second transaction to rollback or commit without making any changes.

  • 写回答

1条回答 默认 最新

  • doujia7094 2014-07-16 22:03
    关注

    Consider simulating record locks with GET_LOCK()

    Choose a name specific to the rows you want locking. e.g. 'numbers_1'.

    Call SELECT GET_LOCK('numbers_1',0) to lock the name 'numbers_1'.. it will return 1 and set the lock if the name is available, or return 0 if the lock is set already. The second parameter is the timeout, 0 for immediate. On a return of 0 you can back out.

    Use SELECT RELEASE_LOCK('numbers_1') when you are finished.

    Be aware; calling GET_LOCK() again in a transaction will release the previously set lock.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?