Home > Article > Backend Development > Example of php multi-threading reading and writing the same file
A piece of code that simulates multi-threaded file processing in PHP programming to implement file read-write locking and unlocking functions. Friends in need can refer to it.
The sample code is as follows: <?php /** * php多线程读写同一文件的代码 * site bbs.it-home.org */ function T_put($filename,$string){ $fp = fopen($filename,’a'); //追加方式打开 if (flock($fp, LOCK_EX)){ //加写锁 fputs($fp,$string); //写文件 flock($fp, LOCK_UN); //解锁 } fclose($fp); } function T_get($filename,$length){ $fp = fopen($filename,’r'); //追加方式打开 if (flock($fp, LOCK_SH)){ //加读锁 $result = fgets($fp,$length); //读取文件 flock($fp, LOCK_UN); //解锁 } fclose($fp); return $result; } ?> |