并发文件读/写 [英] concurrent file read/write

查看:122
本文介绍了并发文件读/写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当收到许多阅读和阅读请求时,会发生什么情况?用PHP写文件?请求是否排队?还是只接受其中一个,其余的都被丢弃?

What happens when many requests are received to read & write to a file in PHP? Do the requests get queued? Or is only one accepted and the rest are discarded?

我打算使用基于文本的点击计数器.

I'm planning to use a text based hit counter.

推荐答案

您会遇到比赛条件的问题

You can encounter the problem of race condition

要避免这种情况,如果只需要简单的附加数据,就可以使用

To avoid this if you only need simple append data you can use

file_put_contents(,,FILE_APPEND|LOCK_EX);

不要担心您的数据完整性.

and don't worry about your data integrity.

如果您需要更复杂的操作,则可以使用 flock (用于简单的读取器/写入器问题)

If you need more complex operation you can use flock (used for simple reader/writer problem)

对于您的PHP脚本计数器,我建议您这样做:

For your PHP script counter I suggest you to do with something like this:

//> Register this impression
file_put_contents( $file, "\n", FILE_APPEND|LOCK_EX );

//> Read the total number of impression
echo count(file($file));

这样,您无需实现阻止机制,就可以使系统和代码脚本更轻

This way you don't have to implement a blocking mechanism and you can keep the system and your code script lighter

为了避免不得不计算array file(),您可以使用以下方法使系统更轻巧:

To avoid to have to count the array file() you can keep the system even lighter with this:

//> Register this impression
file_put_contents( $file, '1', FILE_APPEND|LOCK_EX );

//> Read the total number of impression
echo filesize($file);

基本上,要读取计数器的编号,只需考虑每个印象加1个字节即可读取其文件大小

Basically to read the number of your counter you just need to read its filesize considering each impression add 1 byte to it

这篇关于并发文件读/写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆