PHP文件写入线程问题
在 PHP 网页中,我以写入模式打开文件,读取并删除第一行并关闭文件。 (该文件有 1000 行)
现在,问题是什么,如果有大约 100 个用户连接到该页面,所有人都将以写入模式打开该文件,然后在删除第一行后尝试写入它。 这种情况下会不会出现僵局呢?
供您参考,我们使用带有 IIS 服务器和 PHP5 的 Windows 服务器。
预先感谢您的帮助。
In a PHP webpage, Im opening a file in write mode, reading and than deleting the first line and closing the file. (The file has 1000's of lines)
Now, what the problem is, if there are like 100 users connected to that page, all will be opening that file in write mode and than try to write it after deleting the first line.
Will there be any deadlocks in this situation?
For your information, we are using Windows server with IIS server and PHP5.
Thanks in advance for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 flock 一次仅向一名用户授予对文件的访问权限。
但不要忘记通过 fclose
更新释放文件锁定。考虑这段代码:
运行这段代码两次(它锁定文件 3 秒,所以让我们考虑我们的手动脚本异步运行)。您将看到如下内容:
第一个实例:
第二个:
请注意,第二个实例等待第一个实例释放文件锁。
如果它不符合您的要求,那么......尝试发明其他解决方案,例如:
用户可以读取文件,然后他编辑一行并将其另存为临时文件,其他用户保存他的临时文件等等,一旦所有用户释放文件锁定,您就可以将新文件组成为所有临时文件的补丁(使用保存文件 mtime 来定义哪个文件应该分层)...类似这样的东西...也许...不幸的是,我不是此类任务的专家 - 只是我对如何完成此任务的假设。
Use flock to grant access to file only for one user at a time.
But don't forget release your file lock by fclose
Update. Consider this code:
Run this code twice (it locks file for 3 seconds, so let's consider our manual script run as asynchronous). You will see something like this:
First instance:
Second:
Notice, that second instance waited for first to release file lock.
If it does not comply your requirements, well... try to invent other solution like:
user can read file, then he edit one line and save it as temporary, other user saves his temporary file and so on and once you have all users released file lock, you compose new file as patch of all temporary files on each other (use save files mtime to define which file should stratify other one)... Something like this.... maybe... I'm not the expert in this kind of tasks, unfortunately - just my assumption on how you can get this done.
使用文件锁定,或数据库允许并发访问。否则你会遇到麻烦的。
Use file locking, or a database that allows concurrent access. You will get in trouble otherwise.