PHP mutual exclusion (mutex)

前端 未结 5 867
半阙折子戏
半阙折子戏 2020-11-28 09:37

Read some texts about locking in PHP.
They all, mainly, direct to http://php.net/manual/en/function.flock.php .

This page talks about opening a file on the hard-

5条回答
  •  佛祖请我去吃肉
    2020-11-28 10:08

    I recently created my own simple implementation of a mutex-like mechanism using the flock function of PHP. Of course the code below can be improved, but it is working for most use cases.

    function mutex_lock($id, $wait=10)
    {
      $resource = fopen(storage_path("app/".$id.".lck"),"w");
    
      $lock = false;
      for($i = 0; $i < $wait && !($lock = flock($resource,LOCK_EX|LOCK_NB)); $i++)
      {
        sleep(1);
      }
    
      if(!$lock)
      {
        trigger_error("Not able to create a lock in $wait seconds");
      }
    
      return $resource;
    }
    
    function mutex_unlock($id, $resource)
    {
      $result = flock($resource,LOCK_UN);
      fclose($resource);
    
      @unlink(storage_path("app/".$id.".lck"));
    
      return $result;
    }
    

提交回复
热议问题