是否可以在同一时间读取和写入文件? [英] Is it possible to read and write in file at the same time?
问题描述
- ThreadA将从某个套接字读取数据,并将数据写入MyFile.txt
- ThreadB将读取MyFile,当它到达最后时,它将循环直到MyFile中有新的数据可用(因为我不想重新打开MyFile.txt ,并失去了时间,所以我到达我所在的位置..)。
是否有可能做这样的事情?
如果不是,还有另外一种方法可以做这样的事情吗? 解决方案
您提到的问题是一个着名的生产者消费者问题
常见的解决方法是使用 BlockingQueue
真实世界的一个例子是 AjaxYahooSearchEngineMonitor
线程B做的是,它将从中获取项目逐一排队,并对其进行处理。
当队列中没有项目时,线程B就会在那里等待。请参阅源代码的第83行。
Here's the scenario:
- ThreadA is going to read from some socket, and write data to "MyFile.txt"
- ThreadB is going to read "MyFile", and when it reaches the end, it will loops until new data are available in MyFile (because i don't want to re-open "MyFile.txt", and lose the time so i reach the position from where i was..).
Is it possible to do such a thing ?
If not, is there another way to do such a thing ?
The problem you mention is a famous Producer Consumer Problem
Common solution to this is to use BlockingQueue
An example of real world usage is in AjaxYahooSearchEngineMonitor
What Thread A does is, it will submit a string to queue, and then return immediately.
What Thread B does is, it will pick up the item from queue one by one, and process them. When there is no item in the queue, Thread B will just wait there. See line 83 of the source code.
这篇关于是否可以在同一时间读取和写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!