English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The existence of lock mechanism is due to resource competition caused by concurrency. 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 lock mechanisms, PHP's file lock is also to deal with resource competition. Suppose a scenario, under the condition of high concurrency, multiple ordered writes to the file tail through fwrite, what will happen without locking? Multiple ordered write operations are equivalent to a transaction, and we need to ensure the integrity of this transaction at this time.
If we have two programs writing data to a file at the same time, to ensure data integrity, we can add a file lock, let the program1execute, the program1After execution, unlock and then let the program2Implementation as follows:
$fp = fopen('test.txt',"a"); $count = 10; if (flock($fp, LOCK_EX)) { for($i=1;$i<$count;$i++{ fwrite($fp, 'text2_$i.rn"); echo "test2".date('h:i:s') . " "; sleep(1); echo "test2".date('h:i:s'); } flock($fp , LOCK_UN); } echo "Couldn't lock the file !"; } fclose($fp);
Declaration: The content of this article is from the network, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report via email to codebox.com (replace # with @) and provide relevant evidence. Once verified, the website will immediately delete the infringing content.