PHP lock function for concurrent operations. There is a need: When a file is generated, multiple users have the permission to generate the file to prevent errors in the generated results due to concurrency, and the generated process needs to be locked, there is a need: When a file is generated, multiple users have the permission to generate the file to prevent errors in the generated results due to concurrency, and the generated process needs to be locked, only one user is allowed to perform operations within a period of time. a lock is required to lock the operation process. When the cache is used, the cache failure may cause most concurrent requests to penetrate to the database instantly. at this time, you also need to lock the operation in the same concurrency process.
In the above two cases, the solution is to lock the processing process, and implement the following through PHP:
The memory lock and file lock of the Eaccelerator are used. The principle is to determine whether the EAccelerator is installed in the system. If yes, the memory lock is used. If no Eaccelerator exists, the file lock is implemented. Multiple locks can be directly processed in parallel based on different imported keys, similar to the row-level locks of Innodb.
The specific classes are as follows:
EAccelerator = function_exists ("eaccelerator_lock"); if (! $ This-> eAccelerator) {$ this-> path = $ path. ($ this-> _ mycrc32 ($ name) % $ this-> hashNum).'.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... */public 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) ;}}}?>
Use:
$ Lock = new CacheLock ('key _ name'); $ lock-> lock (); // logic here $ lock-> unlock (); // note that the write permission is required for the path of the file lock.
Success ,...