dongwopu8210 2011-02-05 18:55
浏览 83
已采纳

PHP MySQL get_lock

In a script I'm trying to check whether the same script is already running using MySQL GET_LOCK. The problem is, when a script tries to get lock, which isn't free, it blocks forever regardless of the parameter I provide.

<?php

class Controller_Refresher extends Controller {
    public function action_run($key) {
        echo date('H:i:s'."
", time());
        $this->die_if_running();
        $this->run();
        echo date('H:i:s'."
", time());
    }

    private function die_if_running() {
        $result = DB::query(Database::SELECT, "SELECT IS_FREE_LOCK('refresher_running') AS free")->execute();
        if (! intval($result[0]['free'])) die('Running already');
        $result = DB::query(Database::SELECT, "SELECT GET_LOCK('refresher_running', 1)")->execute();
    }

    private function run() {
        echo "Starting
";
        ob_flush();
        sleep(10);

        DB::query(Database::SELECT, "SELECT RELEASE_LOCK('refresher_running')")->execute();
    }
}

When I run this in 2 tabs in browser, I get e.g.:

-tab 1-
20:48:16
Starting
20:48:26
-tab 2-
20:48:27
Starting
20:48:37

While what I want to do is to make the second tab die('Running already');.

  • 写回答

2条回答 默认 最新

  • dongtui2029 2013-01-02 21:43
    关注

    Watch out - this problem might actually be caused by php locking the session file:

    https://stackoverflow.com/a/5487811/539149

    So you should call session_write_close() before any code that needs to run concurrently. I discovered this after trying this Mutex class:

    http://code.google.com/p/mutex-for-php/

    The class worked great but my php scripts were still running one by one!

    Also, you don't need IS_FREE_LOCK(). Just call GET_LOCK('refresher_running', 0) and it will either return 1 if it gives you the lock or 0 if the lock is taken. It's more atomic that way. Of course, lock timeouts can still be useful in certain situations, like when you want to queue up tasks, but watch out for the script timing out if you get too many simultaneous requests.

    Zack Morris

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)