问题描述
如何写入可以由多种来源(可能在并行方式)访问的文本文件,确保没有写操作丢失
像,如果两种不同的方法在同一时刻将文件写入,这可能导致问题。该simples溶液(不是非常快,不是很优雅)将锁定的文件,同时开始处理(创建一个.lock文件或类似),并释放它(删除锁),而写入完成。
在开始写,我想如果.lock检查文件是否存在,延缓写入到文件被释放。
什么是推荐的模式来遵循这种情况?
感谢
修改
我的意思是过程,就像从不同客户,不同的用户等,在同一程序中没有线程
的
how to write to a text file that can be accessed by multiple sources (possibly in a concurrent way) ensuring that no write operation gets lost?
Like, if two different processes are writing in the same moment to the file, this can lead to problems. The simples solution (not very fast and not very elegant) would be locking the file while beginning the process (create a .lock file or similar) and release it (delete the lock) while the writing is done.
When beginning to write, i would check if the .lock file exists and delay the writing till the file is released.
What is the recommended pattern to follow for this kind of situation?
Thanks
EDITI mean processes, like different programs from different clients, different users and so on, not threads within the same program
The fastest way of synchronizing access between processes is to use Mutexes / Semaphores. This thread answers how to use them, to simulate read-writer lock pattern:http://stackoverflow.com/questions/640122/is-there-a-global-named-reader-writer-lock
这篇关于并发文件写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!