Read and write from a file in a circular buffer fashion

时光总嘲笑我的痴心妄想 提交于 2019-12-24 08:23:52

问题


i need to make a file behave as a circular buffer. From one thread i have to write the data.From another thread i have read from the file. But the size of the file is fixed.

Any idea?


回答1:


Since you have not mentioned the language you will be using, I am only able to provide you with a general answer: Write an abstraction that, when reading past the end of the file, seeks to the beginning of the file and resumes reading there.

Be advised that writing and reading to the file from multiple threads needs proper synchronization.




回答2:


I assume that a thread knows the position of the other thread. In this case the writer can append to the file and increase its position until it arrives at MAXSIZE. Then it should wrap around by seeking to position 0 and continue overwriting the old contents as long as its position is smaller than position of the reader, after that it has to block. At the same time reader can read and wrap around if necessary until it reaches the position of the writer.

In other words it's not much different from the standard circular in memory buffer. Are you sure that using a file is necessary in your case? You might also consider doing some research on the producer-consumer problem.




回答3:


You could also consider using a named pipe.



来源:https://stackoverflow.com/questions/3741888/read-and-write-from-a-file-in-a-circular-buffer-fashion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!