<?PHP/** * Cachelock process lock, mainly used for cache invalidation of single process cache acquisition, to prevent excessive SQL requests through the database * to solve the concurrency of PHP lock control, through the file/eaccelerator inter-process lock * If you do not use Eaccelerator to do file lock processing, will do the corresponding directory to generate corresponding granularity of the lock * using eaccelerator in memory processing, performance is relatively high * different locks in parallel execution, similar to the MySQL InnoDB row-level lock * This class made a few changes on the basis of Sunli's Phplock http://code.google.com/p/phplock * @author Yangxinqi **/namespace Common\business; classphplock{//file Lock Storage path Private $path=NULL; //file handle Private $fp=NULL; //Lock grain Size, the larger the size of the smaller Private $hashNum= 100; //Cache Key Private $name; //is there a eaccelerator flag Private $eAccelerator=false; /** * constructor * The storage path of the incoming lock, and the name of the cache key, so that concurrent * @param string $path Lock storage directory with "/" End * @param string $name Cache Key*/ Public function__construct ($name,$path= ' lock\\ ') { $app _path=Str_replace(' thinkphp/', ',Think_path); $is _cli=Php_sapi_name(); if($is _cli= = ' CLI ' | |$is _cli= = ' Cli_server ') { $app _path=Trim(App_path, '. ')); } Else { $app _path=$app _path.Trim(App_path, '. ')); } $path=$app _path.‘ /common/business/lockfile/'; if(!file_exists($path)) { mkdir($path); chmod($path, 777); } //$path. = '/protected/runtime/cache/'; Determine if there is a eaccelerator, where eaccelerator can be used to improve the efficiency of the memory lock $this->eaccelerator =function_exists("Eaccelerator_lock"); if(!$this-eaccelerator) { //$this->path = $path. ($this->_mycrc32 ($name)% $this->hashnum). TXT '; $this->path =$path.SHA1($name).‘. txt; } $this->name =$name; } /** * CRC32 * CRC32 package * @param int $string * @return int*/ Private function_MYCRC32 ($string) { $CRC=ABS(CRC32($string)); if($CRC& 0x80000000) { $CRC^= 0xFFFFFFFF; $CRC+ = 1; } return $CRC; } /** * Plus lock * Enter description here ...*/ Public functionLock () {//Open the file lock if the EA memory lock cannot be opened if(!$this-eaccelerator) { //Configure directory permissions to write $this->FP =fopen($this->path, ' w+ '); if($this->FP = = =false) { return false; } return Flock($this->FP,lock_ex); }Else{ returnEaccelerator_lock ($this-name); } } /** * Unlock * Enter description here ...*/ Public functionunlock () {if(!$this-eaccelerator) { if($this->FP!==false) { Flock($this->FP,Lock_un); Clearstatcache(); } //to close fclose($this-FP); }Else{ returnEaccelerator_unlock ($this-name); } }}
PHP process Lock