Home >Backend Development >PHP Tutorial >Example of php multi-threading reading and writing the same file

Example of php multi-threading reading and writing the same file

WBOY
WBOYOriginal
2016-07-25 09:00:20987browse
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;
}
?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn