使用PHP独占访问功能

时间:2015-02-18 09:15:24

标签: php codeigniter rest curl

我试图在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;
}

2 个答案:

答案 0 :(得分:2)

有用的Thanx

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

Mutex 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);

}

答案 1 :(得分:0)

您只需使用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