Niahm
Niahm

Reputation: 396

Exclusive access to function using PHP

I'm trying to call GetAllDomains in a codeigniter library, but when 2 calls happens simultaneously this method throw errors, any solution to call it exclusively or using mutex, the first user call this method and the others wait until release. the code that call 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 function:

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

Upvotes: 1

Views: 462

Answers (2)

Niahm
Niahm

Reputation: 396

Thanx that was useful

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

}

Upvotes: 2

sectus
sectus

Reputation: 15464

You could simply use 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);

Or mysql getLock with similar algorithm.

Upvotes: 0

Related Questions