• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
红尘一梦丶转瞬空
博客园    首页    新随笔    联系   管理    订阅  订阅

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;
    }
}

posted @ 2019-07-09 15:04  红尘一梦丶转瞬空  阅读(1156)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3