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 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动