更新时间:2023-02-02 21:18:11
您可以尝试php的flock变体( http: //www.php.net/flock )
You could try php's variant of flock (http://www.php.net/flock)
我会设想类似的内容(这假设文件/tmp/counter.txt已经存在并且文件中有一个计数器):
I would envision something similar to (this assumes that the file /tmp/counter.txt already exists and has a counter in the file):
<?php
$fp = fopen("/tmp/counter.txt", "r+");
echo "Attempt to lock\n";
if (flock($fp, LOCK_EX)) {
echo "Locked\n";
// Read current value of the counter and increment
$cntr = fread($fp, 80);
$cntr = intval($cntr) + 1;
// Pause to prove that race condition doesn't exist
sleep(5);
// Write new value to the file
ftruncate($fp, 0);
fseek($fp, 0, SEEK_SET);
fwrite($fp, $cntr);
flock($fp, LOCK_UN); // release the lock
fclose($fp);
}
?>