php使用flock阻塞寫入檔案和非阻塞寫入檔案的實例講解:
阻塞寫入程式碼:(所有程式會等待上次程式執行結束才會執行,30秒會逾時)
<?php$file = fopen("test.txt","w+"); $t1 = microtime(TRUE);if (flock($file,LOCK_EX)) { sleep(10); fwrite($file,"Write something"); flock($file,LOCK_UN); echo "Ok locking file!"; }else{ echo "Error locking file!"; } fclose($file); $t2 = microtime(TRUE);echo sprintf("%.6f",($t2-$t1));
非阻塞寫入程式碼:(只要檔案被佔用,則顯示Error locking file!):
<?php$file = fopen("test.txt","a+"); $t1 = microtime(TRUE);if (flock($file,LOCK_EX|LOCK_NB)) { sleep(10); fwrite($file,"Write something"); flock($file,LOCK_UN); echo "Ok locking file!"; }else{ echo "Error locking file!"; } fclose($file); $t2 = microtime(TRUE);echo sprintf("%.6f",($t2-$t1));
以上是php使用flock阻塞和非阻塞檔案寫入的實例講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!