我写了这个计数器,但是在每小时大约 100-200 次唯一点击的负载下存在一个奇怪的问题。计数重置为大约“120500”的奇怪值,并从那里继续计数,直到稍后重置为相同的值。现在,我会理解一个零值,但是 120500 来自哪里?这是完整的计数器代码:
<?php
class Counter {
public $currentCount;
private $countFile;
public function __construct($file) {
if(!file_exists($file)) {
$fp = fopen($file, 'w');
fwrite($fp, '1');
fclose($fp);
}
$this->countFile = $file;
$this->currentCount = file_get_contents($this->countFile);
}
public function incrementPerSession() {
if(isset($_SESSION['visitWritten'])) {
echo $this->currentCount;
} else {
$count = $this->currentCount + 1;
$this->writeNewCount($count);
echo $count;
}
}
private function writeNewCount($count) {
$delay = rand(10000, 80000);
$fp = fopen($this->countFile, 'w');
if(flock($fp, LOCK_EX)) { // PHP locks are not reliable.
usleep($delay); // usleep() works as a workaround and prevents resets to zero
fwrite($fp, $count);
flock($fp, LOCK_UN);
$_SESSION['visitWritten'] = true;
} else {
echo 'Counter: Could not write to file';
}
fclose($fp);
}
}
?>
这只是偶尔发生,我认为这与同时写入有关。会话变量“visitWritten”未在站点的其他任何地方使用。我怎样才能提高这门课?