PHP利用flock实现给文件加锁的功能详解
程序员文章站
2022-03-16 13:33:09
...
<?php
$file = fopen("test.txt","w+");
if (flock($file,LOCK_EX))
{
fwrite($file,"Write something");
flock($file,LOCK_UN);
}
else
{
echo "Error locking file!";
}
fclose($file);
?>
例如:请写一段PHP代码,确保多个进程同时写入同一个文件成功
function writeData($path, $mode,$data) { $fp = fopen($path, $mode); $retries = 0; $max_retries = 100; do{ if ($retries > 0) { usleep(rand(1, 10000)); } $retries += 1; }while (!flock($fp, LOCK_EX) and $retries<= $max_retries); if ($retries == $max_retries) { return false; } fwrite($fp, "$data\n"); flock($fp, LOCK_UN); fclose($fp); return true; }
以上就是PHP利用flock实现给文件加锁的功能详解的详细内容,更多请关注其它相关文章!
下一篇: php技术是什么?