Analysis and research of PHP process lock-in problem _php skills

Source: Internet
Author: User
Tags flock message queue usleep

1. Distinguish between read lock and write lock.
If you use a write lock every time, it is not efficient to queue up multiple processes to read a file.
2. Distinguish between blocking and non-blocking modes.
In general, if a process is writing a file, another process should be blocked, but, in many cases, we can do something else first,
Then judge if someone else is writing the file, and if not, add the data, which is more efficient.
3. Fixed bugs on Linux for locked files, especially on the GFS file system.
The code is as follows:

Copy Code code as follows:

<?php
Class File_lock
{
Private $name;
Private $handle;
Private $mode;
function __construct ($filename, $mode = ' a+b ')
{
Global $php _errormsg;
$this->name = $filename;
$path = dirname ($this->name);
if ($path = = '. ' | |!is_dir ($path)) {
Global $config _file_lock_path;
$this->name = str_replace (Array ("/", "\"), Array ("_", "_"), $this->name);
if ($config _file_lock_path = = null) {
$this->name = dirname (__file__). "/lock/". $this->name;
} else {
$this->name = $config _file_lock_path. "/" . $this->name;
}
}
$this->mode = $mode;
$this->handle = @fopen ($this->name, $mode);
if ($this->handle = = False) {
throw new Exception ($php _errormsg);
}
}
Public Function Close ()
{
if ($this->handle!== null) {
@fclose ($this->handle);
$this->handle = null;
}
}
Public Function __destruct ()
{
$this->close ();
}
Public function Lock ($lockType, $nonBlockingLock = False)
{
if ($nonBlockingLock) {
Return Flock ($this->handle, $lockType | LOCK_NB);
} else {
Return Flock ($this->handle, $lockType);
}
}
Public Function Readlock ()
{
return $this->lock (LOCK_SH);
}
Public Function Writelock ($wait = 0.1)
{
$startTime = Microtime (true);
$canWrite = false;
do {
$canWrite = Flock ($this->handle, LOCK_EX);
if (! $canWrite) {
Usleep (rand (10, 1000));
}
while ((! $canWrite) && ((Microtime (True)-$startTime) < $wait);
}
/**
* If you are want ' t to log the number under Multi-thread system,
* Please open the lock and use a + mod. Then fopen the file won't
* Destroy the data.
*
* This function is increment a delt value, and save to the file.
*
* @param int $delt
* @return int
*/
Public Function Increment ($delt = 1)
{
$n = $this->get ();
$n + + $delt;
$this->set ($n);
return $n;
}
Public function Get ()
{
Fseek ($this->handle, 0);
return (int) fgets ($this->handle);
}
Public function set ($value)
{
Ftruncate ($this->handle, 0);
Return fwrite ($this->handle, (string) $value);
}
Public function unlock ()
{
if ($this->handle!== null) {
Return Flock ($this->handle, Lock_un);
} else {
return true;
}
}
}
?>

Test code:
Copy Code code as follows:

<?php
/**
* Write-Lock test
* Open Thread 1
*/
Require ("file_lock.php");
$lock = new File_lock (dirname (dirname (__file__)). "/filelock.lock");
/** a single thread lock speed of 1s clock 30,000 times. **/
/** Two threads write, 20,000 of the data is about 7s clock.
/** a thread to write, 10,000 of the data is about 3.9s clock, incredibly two files are written at the same time, to be a little faster *
/** do not lock, a process to write about 2.8s clock, lock has a price. */
/** do not lock, two process distribution is not very uniform, and most of them conflict
$lock->writelock ();
$lock->increment ();
$lock->unlock ();
while ($lock->get () < 2) {
Usleep (1000);
}
Sleep (1);
echo "begin to runing \ n";
$t 1 = microtime (true);
for ($i = 0; $i < 10000; $i + +)
{
$lock->writelock ();
$lock->increment (1);
$lock->unlock ();
}
$t 2 = Microtime (True)-$t 1;
echo $t 2;
?>

I added a increment function that allows for simple thread synchronization, allowing two processes to execute a piece of code at the same time, which, of course, has some error
The error here is 0.001s.
You can implement thread-safe Message Queuing by simply using this class in the previous Memcache message queue.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.