Sometimes your php script may need thread safety guarantee, such as when performing file writing operations. This article provides file locking functions and usage examples. The file locking function can also be used to obtain exclusive processing space to prevent synchronization errors in script execution.
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 examples
$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 transactions that require exclusive processing are performed here.
// ... ...
// Transaction completed.
unlock_thisfile($lockhandle,$tmpFileStr);
}
?>