使用 PHP 独占访问函数

Exclusive access to function using PHP

我正在尝试在 codeigniter 库中调用 GetAllDomains,但是当 2 个调用同时发生时,此方法会抛出错误,任何以独占方式调用它或使用互斥锁的解决方案,第一个用户调用此方法,其他用户等到释放. 调用 GetAllDomains 的代码:

public function index(){

    $this->data['menu'] = 1;
    $this->data['message'] = $this->session->flashdata('message');

    $domains = $this->exchange_api->GetAllDomains();

    if(is_null($domains)){ 
        $domains = array();
    }

    var_dump($domains);

}

GetAllDomains 函数:

public function GetAllDomains(){
    $domains = $this->ci->rest->post('GetAllDomain');
    return isset($domains->Result) && $domains->Result == 1 ? $domains->Param: null;
}

您可以简单地使用 flock

$fp = fopen("/tmp/lock.txt", "w+");
if (flock($fp, LOCK_EX)) { // lock
    sleep(10); // your function execute
    flock($fp, LOCK_UN); // unlock
} else {
    echo "failed";
}
fclose($fp);

或mysql getLock 算法类似。

谢谢,很有用

public function GetAllDomains(){

    $this->ci->mutex->Lock();
    $domains = $this->ci->rest->post('GetAllDomain');
    $this->ci->mutex->Release();

    return isset($domains->Result) && $domains->Result == 1 ? $domains->Param: null;
}

互斥Class:

public function Lock(){

    $this->fp = fopen($this->lockFilePath, "w+");
    flock($this->fp, LOCK_EX);

}

public function Release(){

    flock($this->fp, LOCK_UN);
    fclose($this->fp);

}