[Open Source] phplock (PHP process lock) V1.0 beta1
Because PHP does not support built-in locks in multi-process mode (concurrent web access), it is prone to concurrency problems after processing some resources.
In web development, we often cache time-consuming operations on our databases, but there may be a trap. When the cache becomes invalid, a large number of accesses will be marked as invalid cache, all go to the backend to query the database, resulting in
At the same time, a large number of database queries are time-consuming, resulting in database downtime and other problems. This issue is hidden and not easy to find. This project is mainly used to solve the problem of PHP inter-process lock.
Example:
<? PHP
/**
* Test example: If you open two pages at the same time, you can find that only one page can always enter the lock interval. Code
* @ Link http://code.google.com/p/phplock/
* @ Author sunli
* @ Svnversion $ ID: Test. php 2 2009-11-24 07: 14: 27z sunli1223 $
* @ Version V1.0 beta1
* @ License Apache license version 2.0
* @ Copyright sunli1223@gmail.com
*/
Require 'class. phplock. php ';
$ Lock = new phplock ('lock/', 'lockname ');
$ Lock-> startlock ();
$ Lock-> startlock ();
// Process Code
Echo "<span> lock </span> <br/> \ r \ n ";
Ob_end_flush ();
Flush ();
Ob_flush ();
Sleep (5); // sleep for 20 seconds, simulating concurrent operations
Echo "execution completed <br/> \ r \ n ";
$ Lock-> unlock ();
$ Lock-> endlock ();
Echo "lock release completed <br/> \ r \ n ";
/**
* Cache operations
*
* @ Return $ Array
*/
Function getcache ($ key ){
Return $ cache;
}
/**
* Set Cache
*
* @ Param string $ key
* @ Param array $ Value
*/
Function setcache ($ key, $ value ){
}
$ Cache = getcache ($ key );
If (! $ Cache ){
// The cache does not exist and the lock starts.
$ Lock = new phplock ('lock/', $ key );
$ Lock-> startlock ();
$ Lock-> startlock ();
// Try to determine whether there is data in the cache and there may be access to re-cache, so you do not need to query the database again
$ Cache = getcache ();
If (! $ Cache ){
// Database query operation, code omitted
$ DATA = $ dbdata;
Setcache ($ key, $ data );
}
// Release the lock
$ Lock-> unlock ();
$ Lock-> endlock ();
}
?>
Project address: http://code.google.com/p/phplock/