以循环缓冲区方式读取和写入文件

发布于 2024-09-23 23:56:07 字数 78 浏览 4 评论 0原文

我需要使文件充当循环缓冲区。我必须从一个线程写入数据。从另一个线程我已从文件中读取数据。但文件的大小是固定的。

有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

誰認得朕 2024-09-30 23:56:07

由于您没有提到您将使用的语言,我只能为您提供一个笼统的答案:编写一个抽象,当读取文件末尾之后,查找文件的开头并从那里继续读取。

请注意,从多个线程写入和读取文件需要正确的同步。

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.

因为看清所以看轻 2024-09-30 23:56:07

我假设一个线程知道另一个线程的位置。在这种情况下,编写器可以追加到文件并增加其位置,直到达到 MAXSIZE。然后它应该通过寻找位置 0 来回绕并继续覆盖旧内容,只要它的位置小于读取器的位置,之后它必须阻塞。同时,如果需要,读者可以阅读并回绕,直到到达作者的位置。

换句话说,它与内存缓冲区中的标准循环没有太大区别。您确定在您的情况下需要使用文件吗?您还可以考虑对生产者-消费者问题进行一些研究。

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.

我早已燃尽 2024-09-30 23:56:07

您还可以考虑使用命名管道。

You could also consider using a named pipe.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文