本文以實例講述了PHP文件寫入方法,以應對多線程寫入,具體代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
function file_write( $file_name , $text , $mode = 'a' , $timeout =30){ $handle = fopen ( $file_name , $mode ); while ( $timeout >0){ $timeout --; sleep(1); } } if ( $timeout > 0 ){ fwrite( $handle , $text . '\n' ); flock ( $handle , LOCK_UN); fclose( $handle ); //釋放鎖定操作 return true; } return false; } |
其中flock(int $handle, int $operation)函數(shù)操作的 handle 必須是一個已經(jīng)打開的文件指針。
operation 可以是以下值之一:
要取得共享鎖定(讀取的程序),將 operation 設為 LOCK_SH(PHP 4.0.1 以前的版本設置為 1)。
要取得獨占鎖定(寫入的程序),將 operation 設為 LOCK_EX(PHP 4.0.1 以前的版本中設置為 2)。
要釋放鎖定(無論共享或獨占),將 operation 設為 LOCK_UN(PHP 4.0.1 以前的版本中設置為 3)。
如果不希望 flock() 在鎖定時堵塞,則給 operation 加上 LOCK_NB(PHP 4.0.1 以前的版本中設置為 4)。
此外, fclose()用來釋放鎖定操作,在代碼執(zhí)行完畢時調(diào)用。