mysql insert race condition

后端 未结 8 1469
暗喜
暗喜 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条回答
  •  旧时难觅i
    2020-12-09 06:30

    I ran into the same problem and searched the Net for a moment :)

    Finally I came up with solution similar to method to creating filesystem objects in shared (temporary) directories to securely open temporary files:

    $exists = $success = false;
    do{
     $exists = check();// select a row in the table 
     if (!$exists)
      $success = create_record();
      if ($success){
       $exists = true;
      }else if ($success != ERROR_DUP_ROW){
        log_error("failed to create row not 'coz DUP_ROW!");
        break;
      }else{
        //probably other process has already created the record,
        //so try check again if exists
      }
    }while(!$exists)
    

    Don't be afraid of busy-loop - normally it will execute once or twice.

提交回复
热议问题