/*
*lock_thisfile: Obtain exclusive lock
*@param $tmpFileStr The file name used as the shared lock file (you can give it any name)
*@param $locktype lock type, the default is false (non-blocking, that is, once the lock fails, it will directly return false). If set to true, it will wait for the lock to be successful before returning
*@return If the lock is successful, the lock instance is returned (this parameter is required when using the unlock_thisfile method), if the lock fails, false is returned.
*/
function lock_thisfile($tmpFileStr,$locktype=false){
if($locktype == false)
$locktype = LOCK_EX|LOCK_NB;
$can_write = 0;
$lockfp = @fopen($tmpFileStr.".lock","w");
if($lockfp){
$can_write = @flock($lockfp,$locktype);
}
if($can_write){
return $lockfp;
}
else{
if($lockfp){
@fclose($lockfp);
@unlink($tmpFileStr.".lock");
}
return false;
}
}
/**
*unlock_thisfile: Unlock the previously obtained lock instance
*@param $fp The return value of the lock_thisfile method
*@param $tmpFileStr The file name used as the shared lock file (you can give it any name)
*/
function unlock_thisfile($fp,$tmpFileStr){
@flock($fp,LOCK_UN);
@fclose($fp);
@fclose($fp);
@unlink($tmpFileStr.".lock");
}
?>
// Usage example
$tmpFileStr = "/tmp/mylock.loc";
// Wait for the operation permission to be obtained. If you want to return immediately, set the second parameter to false.
$lockhandle = lock_thisfile($tmpFileStr,true);
if($lockhandle){
// All transaction processing that needs to be exclusive is done here.
// ... ...
// Transaction completed.
unlock_thisfile($lockhandle,$tmpFileStr);
}
?>