Thinkphp文件锁处理高并发

namespace appindexcontroller;
use thinkController;
use thinkCache;


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;
    }
}
经验分享 程序员 微信小程序 职场和发展