Home Backend Development PHP Tutorial Analysis and Research on PHP Process Locking Problem_PHP Tutorial

Analysis and Research on PHP Process Locking Problem_PHP Tutorial

Jul 21, 2016 pm 03:42 PM
php use Write distinguish and Multiple read read process locking question

1. Distinguish between read lock and write lock.
If write locking is used every time, multiple processes will have to queue up to read a file, which is definitely not efficient.
2. Distinguish between blocking and non-blocking modes.
Generally speaking, if one process is writing a file, the other process should be blocked. However, many times, we can do something else first,
and then determine whether anyone else is there. Write the file, and if it doesn't exist, add the data, which is more efficient.
3. Fixed the bug of locking files on Linux, especially the bug on the gfs file system.
The code is as follows:

Copy code The code is as follows:

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 want't to log the number under multi-thread system,
* please open the lock, use a+ mod. then fopen the file will not
* destroy the data.
*
* this function 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 The code is as follows:

/**
* Test write lock
* Open thread 1
*/
require("file_lock.php");
$lock = new File_Lock (dirname(dirname(__FILE__)) . "/FileLock.lock");
/**The locking speed of a single thread is 30,000 times per second. **/
/**Two threads write, 20,000 data, it takes about 7 seconds*/
/**It takes about 3.9 seconds to write 10,000 data with one thread. Actually, two files are written at the same time, which is faster.*/
/**Without locking, it takes about 2.8 seconds for a process to write. There is a price for locking.*/
/**Without locking, the distribution of the two processes is not very even, and most of them conflict.*/
$lock->writeLock();
$lock->increment();
$ lock->unlock();
while ($lock->get() < 2) {
usleep(1000);
}
sleep(1);
echo "begin to running n";
$t1 = microtime(true);
for ($i = 0; $i < 10000; $i++)
{
$lock->writeLock ();
$lock->increment(1);
$lock->unlock();
}
$t2 = microtime(true) - $t1;
echo $t2;
?>

I added an increment function, which can achieve simple thread synchronization and allow two processes to execute a certain code at the same time. Of course, this has a certain error
The error here is 0.001s.
Simply use this class in the previous memcache message queue to implement a thread-safe message queue.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320820.htmlTechArticle1. Distinguish read locks and write locks. If write locking is used every time, multiple processes will have to queue up to read a file, which is definitely not efficient. 2. Distinguish between blocking and non...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles