• php做了个弱统计,写入到文件中,引起并发问题,加锁解决


    开始是使用file_get_contents,和file_put_contents()读取和写入文件,结果当同一时间大量请求时,文件内容就会出现重置为空的现象,导致原始内容丢失

    网上找了个解决办法,经修改如下:

    function pageCount($fileName){
        if ($fp = fopen($fileName, 'r+')) {
            $startTime = microtime();
            do {
                $canWrite = flock($fp, LOCK_EX | LOCK_NB);
                if (!$canWrite) {
                    usleep(round(rand(0, 100) * 1000));
                }
            } while ((!$canWrite) && ((microtime() - $startTime) < 1000));
            if ($canWrite) {
                $count = intval(fgets($fp));
                ++$count;
                ftruncate($fp,0); // 将文件截断到给定的长度 
                rewind($fp); // 倒回文件指针的位置 
                fwrite($fp, $count);
                flock($fp , LOCK_UN);
            }
            fclose($fp);
        }
    }
  • 相关阅读:
    docker
    opencart
    Why is setTimeout(fn, 0) sometimes useful?
    linux下php环境配置
    xampp for linux
    Where to go from here
    freefcw/hustoj Install Guide
    khan academy js
    SDWebImage
    基于OpenCV 的iOS开发
  • 原文地址:https://www.cnblogs.com/benlightning/p/4381519.html
Copyright © 2020-2023  润新知