Detailed introduction to PHP flock file lock_PHP tutorial
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 | ||||||||
fclose($fp);
|
代码如下 | 复制代码 |
?$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); |
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); |
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
