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
Release: 2016-07-25 09:00:20
Original
995 people have browsed it
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;
}
?>
Copy after login


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template