547   PHP

利用flock对文件进行非阻塞绑定独享锁,锁定成功则接着操作文件;如果不成功,随机循环多次直至超过限定次数为止;


function operate_file($file,$mode,$content,$try_time){
	// 打开文件
	$file = fopen($file,$mode);
	$count_time = 0;
	$state = false;
	// 循环取得锁,$try_time循环上限次数,避免死循环
	while($count_time<$try_time){
		$count_time++;
		// 尝试LOCK_EX单独锁定,LOCK_NB非阻塞,避免阻塞导致程序无法执行下去
		if (flock($file,LOCK_EX|LOCK_NB)){
			// 锁定成功
			$state=true;
			break;
		}
		// 等待一会再尝试
		usleep(rand(1,1000));
	}
	if($state){
		// 锁定成功,进行操作
		fwrite($file,$content);
                // 释放锁
		flock($file,LOCK_UN);
		echo 'write successfully:'.$content."\n";
	}else{
		echo 'Lock file failed:'.$content."\n";
	}
	// 关闭文件
	fclose($file);
	return $state;
}


$file = 'test.txt';
$mode = 'a';
$content = 'helloworld';
$try_time = 10;

if(operate_file($file,$mode,$content,$try_time)){
	echo 'true';
}else{
	echo 'false';
}



Leave a Reply

Your email address will not be published. Required fields are marked *