MySQL InnoDB dead lock on SELECT with exclusive lock (FOR UPDATE)

后端 未结 3 1104
野的像风
野的像风 2020-12-19 09:48

I do this to ensure only once instance of this process is running (pseudo code php/mysql innodb):

START TRANSACTION
$rpid = SELECT `value` FROM locks WHERE n         


        
相关标签:
3条回答
  • 2020-12-19 10:26

    Just figured it out thanks to Quassnoi's answer...

    I can do:

    $myPid = posix_getpid();
    $gotIt = false;
    while(true){
      START TRANSACTION;
      $pid = SELECT ... FOR UPDATE; // read pid and get lock on it
      if(mysql_num_rows($result) == 0){
        ROLLBACK;// release lock to avoid deadlock
        INSERT IGNORE INTO locks VALUES('lockname', $myPid);
      }else{
        //pid existed, no insert is needed
        break;
      }
    }
    
    if($pid != $myPid){ //we did not insert that
      if($pid>0 && isRunning($pid)){
        ROLLBACK;
        echo 'another process is running';
        exit;
      }{
        // no other process is running - write $myPid in db
        UPDATE locks SET value = $myPid WHERE name = 'lockname'; // update is safe
        COMMIT;
      }
    }else{
      ROLLBACK; // release lock
    }
    
    0 讨论(0)
  • 2020-12-19 10:27

    Without seeing the actual PHP code, it's hard to be sure - but is it possible that you are not actually using the same database connection between running the SELECT and the INSERT?

    I typically prefer not to use transactions if I can avoid it; your problem could be solved by creating a single database query along the lines of

    insert into locks
    select ('lockname', $pid)
    from locks
    where name not in
    (select name from locks)
    

    By accessing the rows affected, you can see if the process is already running...

    0 讨论(0)
  • 2020-12-19 10:34

    SELECT FOR UPDATE obtains an intent exclusive lock on the table prior to obtaining the exclusive lock on the record.

    Therefore, in this scenario:

    X1: SELECT FOR UPDATE -- holds IX, holds X on 'lock_name'
    X2: SELECT FOR UPDATE -- holds IX, waits for X on 'lock_name'
    X1: INSERT -- holds IX, waits for X for the gap on `id`
    

    a deadlock occurs, since both transactions are holding an IX lock on the table and waiting for an X lock on the records.

    Actually, this very scenario is described in the MySQL manual on locking.

    To work around this, you need to get rid of all indexes except the one you are searching on, that is lock_name.

    Just drop the primary key on id.

    0 讨论(0)
提交回复
热议问题