Home >Backend Development >PHP Tutorial >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.