PHP写/更新Textfile,如果随机有多个线程尝试更新Textfi,则不起作用

2024-10-02 04:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码和文件名 如果我只使用
更新.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); 
    ?>

Tags: 文件txtifusersfilephpfoundtrim
1条回答
网友
1楼 · 发布于 2024-10-02 04:25:06

我会在打开文件后创建一个独占锁,然后在关闭文件前释放锁:

要在文件上创建独占锁,请执行以下操作:

flock($fh, LOCK_EX);

要删除它:

flock($fh, LOCK_UN);

无论如何,您将需要检查其他线程是否已经热锁,因此第一个想法是尝试几次尝试获取锁,如果最终不可能,则通知用户、抛出异常或任何其他操作以避免无限循环:

$fh = fopen("found.txt", "w+");
$attempts = 0;
do {
    $attempts++;
    if ($attempts > 5) {
        // throw exception or return response with http status code = 500
    }
    if ($attempts != 1) {
        sleep(1);
    }
} while (!flock($fh, LOCK_EX));

// rest of your code

file_put_contents('found.txt', $users);
flock($fh, LOCK_UN); // release the lock

fclose($fh);

更新 可能问题仍然存在,因为阅读部分,所以让我们在开始阅读之前创建一个共享锁,并简化代码:

$file = "found.txt";
$fh = fopen($file,'r+');
$gotPokemon = $_GET['pokemon'];

$users = '';
$wouldblock = true;

// we add a shared lock for reading
$locked = flock($fh, LOCK_SH, $wouldblock); // it will wait if locked ($wouldblock = true)
while(!feof($fh)) {
    // your code inside while loop
}

// we add an exclusive lock for writing
flock($fh, LOCK_EX, $wouldblock);
file_put_contents('found.txt', $users);
flock($fh, LOCK_UN); // release the locks

fclose($fh);

让我们看看是否有效

相关问题 更多 >

    热门问题