加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

flow_set_write_buffer或PHP中的文件锁定?

发布时间:2020-12-13 15:57:30 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试建立一个缓存系统,可以尽可能快地写入大块数据(8 KB到200 KB之间). 目前我正在使用类似于下面的代码来应用文件锁定功能: $file_handle=fopen($file_name,"w");flock($file_handle,LOCK_EX);fwrite($file_handle,$all_data);flock($file_handle,LO
我正在尝试建立一个缓存系统,可以尽可能快地写入大块数据(8 KB到200 KB之间).

目前我正在使用类似于下面的代码来应用文件锁定功能:

$file_handle=fopen($file_name,"w");
flock($file_handle,LOCK_EX);
fwrite($file_handle,$all_data);
flock($file_handle,LOCK_UN);
fclose($file_handle);

如果许多进程同时运行相同的脚本,这是一次只允许一个进程写入文件的最佳方式,还是应该包括stream_set_write_buffer($file_handle,0);或者我应该丢弃文件锁定?

解决方法

简而言之:

file_put_contents($file_name,$all_data,LOCK_EX);

很长的故事:
您的代码存在一个问题:“w”模式在获取锁定之前截断文件.如果两个单独的进程截断文件,而不是一个写入200Kb,而另一个写入8Kb,则文件中将剩下192Kb的垃圾.我建议在“c”模式下打开一个文件,并在写完所有数据后最后将其截断:

$file_handle = fopen($file_name,'c');
stream_set_write_buffer($file_handle,0); // try to disable write buffering
flock($file_handle,$all_data); // write to possibly pre-allocated space
ftruncate($file_handle,strlen($all_data)); // remove gabage left from previous write
fflush($file_handle); // flush write buffers if enabled
flock($file_handle,LOCK_UN);
fclose($file_handle);

‘c’ Open the file for writing only. If the file does not exist,it is created. If it exists,it is neither truncated (as opposed to ‘w’),nor the call to this function fails (as is the case with ‘x’). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock()) before attempting to modify the file,as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired,ftruncate() can be used after the lock is requested).

您需要通过调用fflush()或禁用写缓冲来确保在释放锁之前刷新写缓冲区.自stream_set_write_buffer();可能会失败,最好还是有fflush().另请注意,写缓冲旨在提高顺序写入的性能.由于您只执行一次写操作,因此写缓冲区可能会略微降低性能,因此,最好先尝试禁用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读