双缓冲设计I/O同步
如果我的应用程序生成数据很慢但消耗数据很快,那么它是否是双缓冲区实现的良好候选者?基本思想是让生产者填充后台缓冲区,而消费者处理前台缓冲区。 我不希望客户端看起来好像正在等待数据。我想平衡生产和消费。我怎样才能实现这个功能?即使我有一个后台缓冲区线程......它也必须与前台缓冲区线程同步,以便前台缓冲区知道何时有新数据(缓冲区已交换)。如果后台缓冲区线程花费太长时间来生成数据,则前台缓冲区将不得不等待处理它。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的应用程序“缓慢生成数据但快速消耗数据”,那么这将限制您从双缓冲中获得的收益。
如果需要 10 秒来生成一个充满数据的缓冲区,并需要 1 秒来消耗它,那么双缓冲可以将吞吐量提高 10%,但是如果生成和消耗都花费相同的时间,则双缓冲可能会使吞吐量增加一倍。
例如:
顺序处理 = 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:
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