Detailed explanation of PHP file lock usage_PHP tutorial

WBOY
Release: 2016-07-13 17:15:56
Original
860 people have browsed it

The general usage of file locks and mysql table locks in PHP is that only one person can operate it at the same time. This avoids the situation where multiple people operate the same file at the same time, which leads to data loss. Let me explain below. Let me introduce to you how to use PHP file lock.

PHP comes with a file lock function:
bool flock ( int $handle , int $operation [, int &$wouldblock ] )
$handle is the open file pointer;
$operation can be
"LOCK_SH", shared lock; "LOCK_EX", exclusive lock; "LOCK_UN", release the lock; "LOCK_NB", prevent blocking when flock is locked.
Here we mainly talk about "LOCK_EX" and "LOCK_NB".

For example, we have two files, as follows.


flocka.php

The code is as follows Copy code
 代码如下 复制代码

$file = 'temp.txt';
    $fp = fopen($file,'a');
 
    for($i = 0;$i < 5;$i++)
{
fwrite($fp, "11111111n");
sleep(1);
}

fclose($fp);

$file = 'temp.txt';

$fp = fopen($file,'a');

代码如下 复制代码
$file = 'temp.txt';
$fp = fopen($file,'a');

for($i = 0;$i < 5;$i++)
{
fwrite($fp, "22222222n");
}

fclose($fp);
for($i = 0;$i < 5;$i++)

{
            fwrite($fp, "11111111n");
         sleep(1);
}

fclose($fp);


flockb.php
The code is as follows Copy code
$file = 'temp.txt';
$fp = fopen($file,'a');

for($i = 0;$i < 5;$i++)
{
            fwrite($fp, "22222222n");
}

代码如下 复制代码
$file = 'temp.txt';
$fp = fopen($file,'a');

if(flock($fp,LOCK_EX))
{
for($i = 0;$i < 5;$i++)
{
fwrite($fp, "11111111n");
sleep(1);
}
flock($fp,LOCK_UN);
}
fclose($fp);
fclose($fp); <🎜>
<🎜>Run flocka.php first, then flockb.php immediately. <🎜> Result: <🎜> 11111111<🎜> 22222222<🎜> 22222222<🎜> 22222222<🎜> 22222222<🎜> 22222222<🎜> 11111111<🎜> 11111111<🎜> 11111111<🎜> 11111111<🎜> Note that when no file lock is added, the two files will write to the txt file at the same time. <🎜> Let’s modify the code of the two php files. <🎜> flocka.php<🎜>
The code is as follows Copy code
$file = 'temp.txt';< 🎜> $fp = fopen($file,'a');<🎜> <🎜> If(flock($fp,LOCK_EX))<🎜> {<🎜> for($i = 0;$i < 5;$i++)<🎜>             {<🎜>                    fwrite($fp, "11111111n");<🎜>                sleep(1);<🎜> }<🎜> flock($fp,LOCK_UN);<🎜> }<🎜> fclose($fp); <🎜>

flockb.php

代码如下 复制代码
$file = 'temp.txt';
$fp = fopen($file,'a');

if(flock($fp,LOCK_EX))
{
for($i = 0;$i < 5;$i++)
{
fwrite($fp, "22222222n");
}
flock($fp,LOCK_UN);
}

fclose($fp);

Similarly run flocka.php first, and then flockb.php immediately.
You will find that flockb.php is in a waiting state before flocka.php finishes running. Only when flocka.php finishes running, flockb.php will continue to execute.
Output result:
11111111
11111111
11111111
11111111
11111111
22222222
22222222
22222222
22222222
22222222
In addition, when flock is executed, the file lock is automatically released.


There is another way


The following code simply simulates this transaction concurrency state: process1.php

The code is as follows Copy code
代码如下 复制代码
$num = 100;
$filename = "processdata.txt";

$fp = fopen($filename, "a");
for ($i = 0; $i < $num; $i++) {
fwrite($fp, "process1: " . $i . "rn");
usleep(100000);
}
fclose($fp);
?>

$num = 100;

$filename = "processdata.txt";

$fp = fopen($filename, "a");

for ($i = 0; $i < $num; $i++) {
代码如下 复制代码

$num = 100;
$filename = "processdata.txt";

$fp = fopen($filename, "a");
for ($i = 0; $i < $num; $i++) {
fwrite($fp, "process2: " . $i . "rn");
usleep(100000);
}
fclose($fp);
?>

             fwrite($fp, "process1: " . $i . "rn");           usleep(100000); } fclose($fp); ?> We need to execute the first transaction first and write these 100 lines in the processdata.txt file. process2.php
The code is as follows Copy code
$num = 100;<🎜> $filename = "processdata.txt";<🎜> <🎜> $fp = fopen($filename, "a");<🎜> for ($i = 0; $i < $num; $i++) {<🎜> fwrite($fp, "process2: " . $i . "rn");<🎜> usleep(100000);<🎜> }<🎜> fclose($fp);<🎜> ?>

The second transaction continues to write 100 lines to the processdata.txt file.

The second transaction continues to write 100 lines to the processdata.txt file.

Executed multiple times at the same time, although 100 rows were written, the data of transaction 1 and transaction 2 were interleaved, which is not the result we want. What we want is the complete execution of the transaction. At this time, we need a mechanism to ensure that the second transaction is executed after the first transaction is executed. In PHP, the flock function accomplishes this mission. Adding: flock($fp, LOCK_EX); in front of the loops of transaction 1 and transaction 2 can meet our needs and serialize the two transactions.

When a transaction completes flock, because what we added here is LOCK_EX (exclusive lock), all operations on resources will be blocked. Only when the transaction is completed, subsequent transactions will be executed. We can confirm this by outputting the current time.

Regarding appending to the tail, there is a concurrent writing problem in early versions of the Unix system. If you want to append to the tail, you need to lseek the position first and then write. When multiple processes operate at the same time, there will be a problem of overwrite writing due to concurrency. That is, after two processes obtain the tail offset at the same time, they perform write operations one after another, and the subsequent operations will overwrite the previous operations. This problem was later solved by adding the O_APPEND operation when opening, which turned the search and write operations into an atomic operation.

In the implementation of PHP's fopen function, if we use the a parameter to append content to the end of the file, the oflag parameter in the open function call is O_CREAT|O_APPEND, that is, we do not need to worry about concurrent append writing when using the append operation.

Flock file lock is also used in PHP's session default storage implementation. When the session starts, PS_READ_FUNC is called, and the session data file is opened with O_CREAT | O_RDWR | O_BINARY. At this time, flock is called and the write lock is added. If this When other processes access this file (that is, the same user initiates a request for the current file again), it will be displayed that the page is loading and the process is blocked. The starting point of adding a write lock is to ensure that the session operation transactions in this session can be completely executed, prevent interference from other processes, and ensure data consistency. If there is no session modification operation on a page, session_write_close() can be called as early as possible to release the lock.

File lock is a lock for files. In addition to this interpretation, it can also be understood as using files as locks. In actual work, sometimes to ensure the execution of a single process, we will determine whether the file exists before the program is executed. If it does not exist, create an empty file and delete the empty file after the process ends. If it exists, it will not be executed.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628753.htmlTechArticleThe general usage of file lock and mysql table lock in PHP is that only one person can operate it at the same time. This avoids the possibility of multiple people operating the same file at the same time, which may lead to data loss...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!