如果我创建一个基本上加载文本文件“counter.txt”的计数器程序,然后它读取文件,如果它包含一个数字,它将数字增加1并用数字更新文件并保存文件
上述程序的代码可以正常工作,例如每秒执行1次,但问题是在执行时间非常高时开始,例如每秒100次。
我面临的问题是文件内容有时会被删除,有时计数器计数不正确。因此,假设我每秒运行100次执行,但计数只会增加10.我绝对确定所有执行都已完成,因为每次执行都会在递增数字后写入文件,并且有100个文件写入另一个目录中执行次数,但其中的计数仅增加10。
<?php
$File = "counter.txt";
$handle = fopen($File, 'r+') ;
$data = fread($handle, 512) ;
$count = $data + 1;
fseek($handle, 0) ;
fwrite($handle, $count) ;
fclose($handle) ;
?>
答案 0 :(得分:1)
问题是两个文件同时计数。计数器将无法正确设置。你需要确定;该文件一次只能访问一次。
Process1: Reads File and gets 0
Process1: Increments 0 to 1
Process2:Reads File and gets 0
Process1: Writes 1 to File
Process2: Increments 0 to 1
Process2: Write 1 to File
答案 1 :(得分:0)
你好@MasterCassim是对的。
使用flock
(http://php.net/manual/en/function.flock.php)锁定文件
<?php
//some code here
flock($file_handle, LOCK_EX) // <- Your code will pause here until you get the lock for indefinite amount of time or till your script times out
//some code here
?>
答案 2 :(得分:0)
如果您偶然使用了包含php页面的数据库,您可以将计数器放入其中,然后您将只使用SET counter = counter + 1
进行UPDATE语句。