英文:
Is there any way to push to the front of a channel in golang?
问题
在Go语言的通道中,最后推送的元素最后被消费。但是是否有一种方法可以将元素推送到通道的“前面”,以便该元素有机会在顺序之外被消费?假设元素1、2、3、4、5、6、7、8被添加到通道中,并且元素4无法处理(1、2、3已成功处理)。在这种情况下,我希望以某种方式再次将元素4推送到通道中,以便在元素5、6、7、8和后续添加的元素之前有机会被处理(如果它们尚未从通道中取出进行处理)。这可以通过使用阻塞队列轻松实现,但我不想使用它们。
英文:
In golang channels, the element pushed last is consumed last. But is there a way to push element to the "front" of the channel so that the element get a chance to get consumed out of turn? Assume elements 1,2,3,4,5,6,7,8 are added to the channel and element 4 failed to process (1,2,3 are processed successfully). In this case I want to push the element 4 again to the channel in such a way that it may get a chance to get processed before elements 5,6,7,8 and subsequent elements added (if they are not already pulled from the channel for processing). This can be easily achieved using blocking queues. But I don't want to use them.
答案1
得分: 4
没有,没有办法将元素推到通道的“前面”。
英文:
> But is there a way to push element to the "front" of the channel
No there is not.
答案2
得分: 2
不,通道是严格按照先进先出(FIFO)的原则工作的。如果你想要优先级,你需要使用多个通道,或者使用其他数据结构,比如堆(heap):https://golang.org/pkg/container/heap/。
英文:
No, a channel is strictly FIFO. You'll have to play with multiple channels if you want priority, or use some other data structure, like a heap: https://golang.org/pkg/container/heap/.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论