thinkphp3.2文件锁解决并发的一种办法


使用文件锁的方法解决

namespace app\index\controller;
use think\Controller;
use think\Cache;


class Index extends Controller
{
   
    /**
     * 首页
     * */
    public function index(){


        $fp = fopen("lock.txt", "w+");
        if(flock($fp,LOCK_EX))   //锁定当前指针,,,
        {
            //..处理订单


            $stock = $this->findStock();
            if($stock > 0){
                $this->setDec();
            }else{
                return '抢购失败';
            }
            return $stock;
            flock($fp,LOCK_UN);
        }
        fclose($fp);
    }


    /**
     * 查询数据库库存
     * */
    public function findStock(){
        $res = db('info')->where('id',1)->field('stock')->lock(true)->find();
        return $res['stock'];
    }


    /**
     * 减少库存操作
     * */
    public function setDec(){
        $res = db('info')->where('id',1)->setDec('stock',1);
        return $res;
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM