There are two types of file locks: shared locks and exclusive locks, that is, read locks (LOCK_SH) and write locks (LOCK_EX)
File locks are generally used like this:
$fp = fopen("filename", "a"); flock($fp, LOCK_SH) or die("lock error") $str = fread($fp, 1024); flock($fp, LOCK_UN); fclose($fp);
Note that after fwrite, the file is updated immediately, and Instead of waiting for fwrite and then fclose before the file is updated, this can be checked by reading the file after fwrite but before fclose
But when to use lock_ex and when to use lock_sh?
When reading:
If you don’t want dirty data to appear, it is best to use the 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 you read exactly half of it and then it is written by another program, then the second half of the read may not match the first half (the first half is before modification, the second half is after modification)
2. If when reading A shared lock is added (because it is only for reading, there is no need to use an exclusive lock). At this time, other programs start to write. This writing program does not use a lock, so the writing program will directly modify the file, which will also cause the same problem 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 , there are other programs to read at this time, so what will he 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 reader has applied for a shared lock before, the reader will wait for the writer to finish writing abc and release the lock before reading.