双缓冲设计I/O同步

发布于 2024-10-27 08:33:19 字数 543 浏览 6 评论 0原文

如果我的应用程序生成数据很慢但消耗数据很快,那么它是否是双缓冲区实现的良好候选者?基本思想是让生产者填充后台缓冲区,而消费者处理前台缓冲区。 我不希望客户端看起来好像正在等待数据。我想平衡生产和消费。我怎样才能实现这个功能?即使我有一个后台缓冲区线程......它也必须与前台缓冲区线程同步,以便前台缓冲区知道何时有新数据(缓冲区已交换)。如果后台缓冲区线程花费太长时间来生成数据,则前台缓冲区将不得不等待处理它。

void fill_back_buffer() {

   //wait to fill buffer
   //fill back buffer


   //swap buffers and notify other thread
}

void process_data() {

  //wait to see if buffers have been swapped


  //buffers been swapped so send data out
  //while sending data out start filling back buffer with new data
}

If I have an application that that produces data slowly but consumes it quickly, would it be a good candidate for a double buffer implementation? The basic idea would be to have the producer fill the back buffer while the consumer processes the front buffer.
I do not want the client to appear as though it is waiting for data. I want to balance out the producing and the consuming. How can I achieve this functionality? Even if I have a back buffer thread.... it will have to be synchronized with the front buffer thread so the front buffer knows when there is new data (buffers been swapped). If back buffer thread takes too long to produce its data then the front buffer will have to wait to process it.

void fill_back_buffer() {

   //wait to fill buffer
   //fill back buffer


   //swap buffers and notify other thread
}

void process_data() {

  //wait to see if buffers have been swapped


  //buffers been swapped so send data out
  //while sending data out start filling back buffer with new data
}

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

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

发布评论

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

评论(1

若无相欠,怎会相见 2024-11-03 08:33:19

如果您的应用程序“缓慢生成数据但快速消耗数据”,那么这将限制您从双缓冲中获得的收益。

如果需要 10 秒来生成一个充满数据的缓冲区,并需要 1 秒来消耗它,那么双缓冲可以将吞吐量提高 10%,但是如果生成和消耗都花费相同的时间,则双缓冲可能会使吞吐量增加一倍。

例如:

  • Produce_time = 10 秒
  • Consumer_time = 1 秒
  • 缓冲区数量 = 100

顺序处理 = 100 * (10 + 1) = 1,100 秒
双缓冲 = 100 * 10 = 1,000 秒

但是,如果我们更改参数,consume_time = 10 秒:

顺序处理 = 100 * (10 + 10) = 2,000 秒
双缓冲 = 100 * 10 = 1,000 秒

If your application "produces data slowly but consumes it quickly", that's going to limit the gains you can get from double-buffering.

If it takes 10 seconds to produce a buffer full of data, and 1 second to consume it, double-buffering can increase your throughput 10%, but if producing and consuming both take the same amount of time, double-buffering may double your throughput.

For example:

  • produce_time = 10 seconds
  • consume_time = 1 second
  • number of buffers = 100

sequential processing = 100 * (10 + 1) = 1,100 seconds
double-buffered = 100 * 10 = 1,000 seconds

But, if we change the parameters so consume_time = 10 seconds:

sequential processing = 100 * (10 + 10) = 2,000 seconds
double-buffered = 100 * 10 = 1,000 seconds

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