php多线程上下文中安全写文件
提供一个php多线程上下文中安全写文件的实现方法。这个实现没有使用php 的file lock机制,使用的是临时文件机制。多线程中的各个线程都是对各自(每个线程独占一个)的临时文件写,然后再同步到原文件中。
<?php
/**
* @usage: used to offer safe file write operation in multiple threads context, arbitory file type
* @author: Rocky Zhang
* @time: Nov. 11 2009
* @demo[0]: $handler = mfopen($file, 'a+');
* mfwrite($handler, $str);
*/
function mfopen($file, $mode='w+') {
$tempfile = generateTempfile('./tempdir', $file);
preg_match('/b/i', $mode) || ($mode .= 'b'); // 'b' is recommended
if (preg_match('/\w|a/i', $mode) && !is_writable($file)) {
exit("{$file} is not writable!");
}
$filemtime = $filemtime2 = 0;
$tempdir = dirname($tempfile);
is_dir($tempdir) || mkdir($tempdir, 0777);
do { // do-while used to avoid modify in a long time copy
clearstatcache();
$filemtime = filemtime($file);
copy($file, $tempfile);
$filemtime2 = filemtime($file);
} while ( ($filemtime2 - $filemtime) != 0 );
if (!$handler = fopen($tempfile, $mode)) {
exit('Fail on opening tempfile, write authentication is must on temporary dir!');
}
return array(0=>$handler, 1=>$filemtime, 2=>$file, 3=>$tempfile, 4=>$mode);
}
// I do think that this function should be optimized further
function mfwrite(&$handler, $str='') {
if (strlen($str) > 0) {
$num = fwrite($handler[0], $str);
相关文档:
和很多语言不同,在PHP中使用变量之前不需要声明,只需要为变量赋值即可,PHP中的变量名称用$和标识符表示,变量名是区别大小写的。
变量赋值,是指给变量一个具体的数据数据值,对于字符串和数字类型的变量,可以通过"="来实现。
除了直接赋值外,还有两种方式来给变量声明或赋值。一种是变量间的赋值。另一种是引用赋值。 ......
在访问PHP类中的成员变量或方法时,如果被引用的变量或者方法被声明成const或者static,那么就必须使用操作符::,反之如果被引用的变量或者方法没有被声明成const或者static,那么就必须使用操作符->。
另外,如果从类的内部访问const或者static变量或者方法,那么就必须使用自引用的self,反之如果从类的内部访问不为cons ......
用户定义的类,也是学好 PHP 所必备的条件之一。
而 PHP 的类,和其它的面向对象语言比较起来,还算蛮单纯的。
PHP 只有类别 (class)、方法 (method)、属性、以及单一继承 (extensions) 等。
对不习惯使用 C++、Java、Delphi 等面向对象语言来开发程序的用户,不妨先阅读一下有关面向对象概念的书,相信可以带来许多的收 ......