PHP process lock, php process
<? Php/*** CacheLock process lock is mainly used to obtain the cache of a single process when the cache fails, to prevent excessive SQL requests from penetrating the database * used to solve PHP lock Control During concurrency, lock between processes through file/eaccelerator * If eaccelerator is not used, file lock will be generated in the corresponding directory * If eaccelerator is used, it will be processed in the memory, relatively high performance * parallel execution between different locks, similar to mysql innodb row lock * This class on the basis of sunli phplock made a little modification http://code.google.com/p/phplock * @ author yangxinqi **/namespace Common \ Business; class PhpLock {// file lock storage path private $ path = null; // file handle private $ fp = Null; // lock granularity. The larger the granularity, the smaller the granularity. private $ hashNum = 100; // cache key private $ name; // whether the eaccelerator flag exists. private $ eAccelerator = false; /***** constructor * imports the lock storage path and the cache key name, so that concurrent operations can be performed * @ param string $ path lock storage directory, end with "/" * @ 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/'; // determines whether eAccelerator exists, the eAccelerator can be used for Memory Lock to improve efficiency. $ this-> eAccelerator = function_exists ("eaccelerator_lock"); if (! $ This-> eAccelerator) {// $ this-> path = $ path. ($ this-> _ mycrc32 ($ name) % $ this-> hashNum).'.txt '; $ this-> path = paipath.sha1({name=.'.txt';} $ this-> name = $ name ;} /*** crc32 * crc32 encapsulation * @ param int $ string * @ return int */private function _ mycrc32 ($ string) {$ crc = abs (crc32 ($ string); if ($ crc & 0x80000000) {$ crc ^ = 0 xffffffff; $ crc + = 1 ;} return $ crc;}/*** lock * Enter description here... */p Ublic function lock () {// if the ea Memory lock cannot be enabled, enable the file lock if (! $ This-> eAccelerator) {// You can configure the directory permission to write $ this-> fp = fopen ($ this-> path, 'W + '); if ($ this-> fp ==== false) {return false;} return flock ($ this-> fp, LOCK_EX );} else {return eaccelerator_lock ($ this-> name) ;}}/*** unlock * Enter description here... */public function unlock () {if (! $ This-> eAccelerator) {if ($ this-> fp! = False) {flock ($ this-> fp, LOCK_UN); clearstatcache () ;}// close fclose ($ this-> fp );} else {return eaccelerator_unlock ($ this-> name );}}}