我正在循环中从 channel 读取值,如下所示:
for {
capturedFrame := <-capturedFrameChan
remoteCopy(capturedFrame)
}
为了提高效率,我想批量读取这些值,使用如下内容(伪代码):
for {
capturedFrames := <-capturedFrameChan
multipleRemoteCopy(capturedFrames)
}
但我不知道该怎么做。如果我多次调用
capturedFrames := <-capturedFrameChan
它将阻塞。基本上,我想要的是读取
captureFrameChan
中的所有可用值,如果没有可用值,它会像往常一样阻塞。在 Go 中实现这一目标的方法是什么?
最佳答案
这样的事情应该工作:
for {
// we initialize our slice. You may want to add a larger cap to avoid multiple memory allocations on `append`
capturedFrames := make([]Frame, 1)
// We block waiting for a first frame
capturedFrames[0] = <-capturedFrameChan
forLoop:
for {
select {
case buf := <-capturedFrameChan:
// if there is more frame immediately available, we add them to our slice
capturedFrames = append(capturedFrames, buf)
default:
// else we move on without blocking
break forLoop
}
}
multipleRemoteCopy(capturedFrames)
}
关于go - 从 Go 中的 channel 读取多个元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33328000/