这是我的代码和文件名
如果我只使用
更新.php?口袋妖怪=皮卡丘
它更新了我的皮卡丘价值找到.txt+0.0001个
但现在我的问题是,当我有多个线程随机运行时 2个螺纹 更新.php?口袋妖怪=皮卡丘 和 更新.php?口袋妖怪=zaptos
我看到了找到.txt文件 是空的比!! 所以它什么也没写。 所以我猜当打开php文件并向服务器发送另一个请求时,这是一个bug。 我怎样才能解决这个问题这经常发生
你知道吗找到.txt你知道吗
pikachu:2.2122
arktos:0
zaptos:0
lavados:9.2814
blabla:0
你知道吗更新.php你知道吗
<?php
$file = "found.txt";
$fh = fopen($file,'r+');
$gotPokemon = $_GET['pokemon'];
$users = '';
while(!feof($fh)) {
$user = explode(':',fgets($fh));
$pokename = trim($user[0]);
$infound = trim($user[1]);
// check for empty indexes
if (!empty($pokename)) {
if ($pokename == $gotPokemon) {
if ($gotPokemon == "Pikachu"){
$infound+=0.0001;
}
if ($gotPokemon == "Arktos"){
$infound+=0.0001;
}
if ($gotPokemon == "Zaptos"){
$infound+=0.0001;
}
if ($gotPokemon == "Lavados"){
$infound+=0.0001;
}
}
$users .= $pokename . ':' . $infound;
$users .= "\r\n";
}
}
file_put_contents('found.txt', $users);
fclose($fh);
?>
我会在打开文件后创建一个独占锁,然后在关闭文件前释放锁:
要在文件上创建独占锁,请执行以下操作:
要删除它:
无论如何,您将需要检查其他线程是否已经热锁,因此第一个想法是尝试几次尝试获取锁,如果最终不可能,则通知用户、抛出异常或任何其他操作以避免无限循环:
更新 可能问题仍然存在,因为阅读部分,所以让我们在开始阅读之前创建一个共享锁,并简化代码:
让我们看看是否有效
相关问题 更多 >
编程相关推荐