Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to read and write in file at the same time?

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 ?

like image 330
mohamida Avatar asked Oct 19 '10 07:10

mohamida


People also ask

Can we read and write to a file at the same time?

You need a single stream, opened for both reading and writing. NG. The combination of ReadAllText / WriteAllText will have the same problem (another process can access the file in between). A single FileStream works, though.

Can two processes read and write to the same file?

If you try to read at the same time someone else is writing, that's perfectly OK. The only issue is if you are trying to read a block that the writer is writing at the same time. In that cause, the data you get is unpredictable but you should be able to read.

Can I read a file while it is being written?

Most likely, you'll have to make your program open the file, read a small chunk, close the file, and then wait for a bit before reading again. Even then, there's no guarantee that you won't have the file open when the writing process tries to write.

Can we read & write to the stack at the same time?

You can both read and write to it, but the original contents are lost.


1 Answers

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.

like image 55
Cheok Yan Cheng Avatar answered Nov 15 '22 15:11

Cheok Yan Cheng