<?php//using Memache as the prefix for process lock class lock_processlock{//Key protected $sLockKeyPre;
Retry interval protected $iLockRetryInterval;
Number of retries protected $iLockRetryCount;
The expiration time of the lock is protected $iLockCacheTimeout;
The callback function after the lock expiration protected $onLockTimeoutFunc;
The example of Memache protected $oMemcache;
The number of retries protected $iMemcacheRetryCount after the storage memcache failed;
Public function __construct ($onLockTimeoutFunc =null) {$aLockConfig = Get_config (', ' Lock ');
$this->slockkeypre = Self::lock_key_pre;
$this->ilockretryinterval = Self::lock_retry_interval;
$this->ilockretrycount =self::lock_retry_count;
$this->ilockcachetimeout = self::lock_cache_timeout;
$this->imemcacheretrycount = self::lock_cache_timeout;
if (! $onLockTimeoutFunc) {//If the lock is unsuccessful, call the callback function, and if there is no callback function, use the $onLockTimeoutFunc in this class = ' onlocktimeout ';
} $this->onlocktimeoutfunc = $onLockTimeoutFunc; /** Connection Memcache Server/Public function connect () {if (! isset ($this->OMEMCAche)) {$this->omemcache = new Memcache ();
$this->omemcache->connect (' 127.0.0.1 ', 11211);
return $this->omemcache; }/* Add key/Public Addmemcache to Memcache ($sKey, $sValue, $iTimeout) {for ($i = 0; $i < $this->imemcache
RetryCount) {$bRes = $this->omemcache->add ($sKey, $sValue, $iTimeout);
if ($bRes) {return true;
//If the lock is unsuccessful, after sleep, the new lock Usleep ($this->ilockretryinterval*1000);
return false;
}/* Lock/Public Function lock ($sLockID) {$oMemcache = $this->connect (); $sKey = $this->slockkeypre.
$sLockID; Lock if not successful can try a few more for ($i = 0; $i < $this->ilockretrycount $i + +) {//This setting value can be arbitrarily set if ($this-&G
T;addmemcache ($sKey, ' 1 ', $this->ilockcachetimeout)) {return true;
//If the lock is unsuccessful, after sleep, the new lock Usleep ($this->ilockretryinterval*1000); If it is not successful, the lock fails and the callback function is invoked. That is, the action to be processed after the failure if (is_callable $this->onlocktimeoutFunc)) {//Call function Call_user_func ($this->onlocktimeoutfunc);
\ * Unlock operation/Public function unlock ($sLockID) {$oMemcache = $this->connect (); $sKey = $this->slockkeypre.
$sLockID;
Delete key return $this->omemcache->delete ($sKey);
/** If the lock is unsuccessful, perform the following action/Public function onlocktimeout () {echo ("lock timeout");
//Application Instance $oLock = new Lock_processlock ();
$lockResource = "Test";
Lock $oLock->lock ($lockResource);
Unlock $oLock->unlock ($lockResource);