我开发了一个在线游戏。它有一个名为automations.php的文件,负责所有类型的自动化任务,如训练士兵,处理战斗等。我的问题是有时函数会执行两次:
class automation{
function automation(){
if(!file_exists('traning.txt')){
file_put_contents('traning.txt' ,'');
$this->train_soldiers();
}
}
private function train_soldiers(){@unlink('traning.txt');}
}正如你所看到的,train_soldiers应该只执行一次,但当有很多在线玩家时,function会执行两次(针对两个不同的请求)。我的问题是如何解决这个问题?
发布于 2014-03-15 00:05:37
您将需要将该文件保留在那里以备将来的请求:
class automation{
function automation(){
if(!file_exists('traning.txt')){
$fp = fopen('traning.txt', 'r+');
if (flock($fp, LOCK_EX, false)) {
$this->train_soldiers();
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
private function train_soldiers(){/** do all training, don't remove the file**/}
}这样,下一个请求就不会执行了。
更新1:添加了flock功能。如果这不起作用,请告诉我你说的不起作用是什么意思。
https://stackoverflow.com/questions/22410030
复制相似问题