search
HomeBackend DevelopmentPHP TutorialDetailed introduction to PHP flock file lock_PHP tutorial

Detailed introduction to PHP flock file lock_PHP tutorial

Jul 13, 2016 pm 05:14 PM
flockphpforintroduceandintegrityWillconcurrentoperatedocumenteffectivenessmechanismstateofmake sureDetailed explanationLock

In order to ensure the effectiveness and integrity of operations, the concurrent state can be converted into a serial state through the lock mechanism. As one of the locking mechanisms, PHP's file lock is also designed to cope with resource competition. Assume an application scenario. In the case of large concurrency, fwrite is used to write data to the end of the file multiple times in an orderly manner. What will happen without locking? Multiple ordered write operations are equivalent to one transaction, and we need to ensure the integrity of this transaction at this time.

bool flock ( int handle, int operation [, int &wouldblock] );
The handle of the flock() operation must be an open file pointer. operation can be one of the following values:

1. To obtain a shared lock (reader), set operation to LOCK_SH (versions before PHP 4.0.1 are set to 1)
2. To obtain an exclusive lock (writer), set operation to LOCK_EX (set to 2 in versions prior to PHP 4.0.1)
3. To release the lock (whether shared or exclusive), set operation to LOCK_UN (set to 3 in versions prior to PHP 4.0.1)
4. If you don’t want flock() to block when locked, add LOCK_NB to the operation (set to 4 in versions before PHP 4.0.1)

Create two files

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

(1) a.php

?$file = "temp.txt";    
$fp = fopen($file , 'w');    
if(flock($fp , LOCK_EX)){    
     fwrite($fp , "abcn");    
     sleep(10);    
     fwrite($fp , "123n");    
    flock($fp , LOCK_UN);    
}    
fclose($fp);

(2) b.php

?$file = "temp.txt";    
$fp = fopen($file , 'r');    
echo fread($fp , 100);    
fclose($fp);

(1) a.php


?$file = "temp.txt";
$fp = fopen($file , 'w');
if(flock($fp , LOCK_EX)){  
                      fwrite($fp , "abcn");                                                                     sleep(10);
        fwrite($fp, "123n");                                                                                     flock($fp, LOCK_UN);

fclose($fp);

 代码如下 复制代码
?$file = "temp.txt";    
$fp = fopen($file , 'r');    
if(flock($fp , LOCK_EX)){    
    echo fread($fp , 100);    
    flock($fp , LOCK_UN);    
} else{    
    echo "Lock file failed...n";    
}    
fclose($fp);
(2) b.php


?$file = "temp.txt";
$fp = fopen($file , 'r');
echo fread($fp, 100);

fclose($fp);

After running a.php, run b.php immediately and you can see the output:
 代码如下 复制代码
?$file = "temp.txt";    
$fp = fopen($file , 'r');    
if(flock($fp , LOCK_SH | LOCK_NB)){    
    echo fread($fp , 100);    
    flock($fp , LOCK_UN);    
} else{    
    echo "Lock file failed...n";    
}    
fclose($fp);
abc After a.php is finished running, run b.php and you can see the output: abc 123 Obviously, when a.php writes a file, the data is too large and takes a long time. At this time, b.php reads incomplete data Modify b.php to:
The code is as follows Copy code
?$file = "temp.txt"; $fp = fopen($file , 'r'); if(flock($fp , LOCK_EX)){   echo fread($fp, 100); flock($fp, LOCK_UN); } else{  echo "Lock file failed...n"; }  fclose($fp);
After running a.php, run b.php immediately. You can find that b.php will wait until a.php is completed (i.e. 10 seconds later) before displaying: abc 123 The read data is complete, but the time is too long, and he has to wait for the write lock to be released. Modify b.php to:
The code is as follows Copy code
?$file = "temp.txt"; $fp = fopen($file , 'r'); if(flock($fp , LOCK_SH | LOCK_NB)){  echo fread($fp, 100); flock($fp, LOCK_UN); } else{  echo "Lock file failed...n"; }  fclose($fp);

After running a.php, run b.php immediately and you can see the output:
Lock file failed…
It is proved that the lock file failure status can be returned instead of waiting for a long time as above.

Conclusion:

It is recommended to select relevant locks when caching files, otherwise the read data may be incomplete or the data may be written repeatedly.
File_get_contents seems to be unable to select a lock. I don’t know what lock it uses by default. Anyway, the output obtained by not locking is the same as incomplete data.
I want to do file caching, so I only need to know whether there is a write lock, and if so, just check the database.


After multiple simultaneous executions, 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.

But when to use lock_ex and when to use lock_sh?

When reading:

If you do not want dirty data to appear, it is best to use lock_sh shared lock. The following three situations can be considered:
1. If no shared lock is added when reading, then if other programs want to write (regardless of whether the write is locked or not), the write will be successful immediately. If exactly half of it is read and then written by another program, then the second half of the read may not match the first half (the first half is before modification, and the second half is after modification)
2. If a shared lock is added when reading (because it is just reading, there is no need to use an exclusive lock), at this time, other programs start to write, and the writing program does not use the lock, then the writing program will directly modify the file, which will also cause Same question as before
3. The most ideal situation is to lock (lock_sh) when reading and lock (lock_ex) when writing. In this way, the writing program will wait for the reading program to complete before operating, and there will be no rash operations.

When writing:

If multiple writing programs operate on the file at the same time without locking, then part of the final data may be written by program a and part by program b
If it is locked when writing, and other programs come to read it at this time, what will it read?
1. If the reader does not apply for a shared lock, then it will read dirty data. For example, when writing a program, you need to write three parts: a, b, and c. After writing a, what you read at this time is a. If you continue to write b, what you read is ab. Then you write c. What you read at this time is abc. .
2. If the reading program has applied for a shared lock before, the reading program will wait for the writing program to finish writing abc and release the lock before reading.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628961.htmlTechArticleIn order to ensure the validity and integrity of the operation, the concurrent state can be converted into a serial state through the lock mechanism. As one of the locking mechanisms, PHP's file lock is also designed to cope with resource competition. ...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.