<?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
");
flock($fp, LOCK_UN);
fclose($fp);
return true;
}| 欢迎光临 一起源码网 (https://www.171739.xyz/) | Powered by Discuz! X3.3 |