英文:
Variable length channel create
问题
我正在尝试编写一个队列,我需要“扩展”我的缓冲通道,有没有一种方法可以在不创建新通道并将元素移动到新通道的情况下实现这一点?
英文:
I am trying to write a queue and I'd need to "grow" my buffered chans, is there a way to do that without having to create a new one and moving the elements to the new one?
答案1
得分: 4
使用标准通道是不可能的。但是,通过使用一个中间的 goroutine 和一些技巧,你可以创建一个等效的实现。然而,它的速度会比原生通道慢一些。在 channels 包中,我实现了一个名为 ResizableChannel
的功能。
- godoc 文档:https://godoc.org/github.com/eapache/channels#ResizableChannel
- GitHub 仓库:https://github.com/eapache/channels/
英文:
It is not possible with standard channels. However by using an intermediate goroutine with a few tricks you can make something that's effectively equivalent. It will, however, be somewhat slower than a native channel. This is implemented as the ResizableChannel
in the channels package (disclaimer: I wrote it).
答案2
得分: 3
为什么你想要增加通道的大小?你是想要一个通道,在没有读取者的情况下仍然可以继续写入吗?
如果是这样的话,你应该使用一个goroutine来拥有队列和两个通道(读取通道和写入通道)。这个goroutine会在内部保持一个项目的切片,其中包含所有已写入的项目(通过写入通道接收),并且它会不断尝试向读取通道写入,直到有读取者从中读取。
希望这对你有所帮助。
英文:
Why would you want to grow the chan size? Are you looking to have a chan where you can keep writing regardless whether there are readers or not?
If so, you should use a goroutine which will own the queue and two chans (read chan and a write chan). The goroutine will keep a slice of items internaly with all the written items (received via write chan) and it will keep attempting to write to the read chan which will block till there are readers reading from it.
hope this helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论