访问者模式 vs Go中的通道

huangapple go评论82阅读模式
英文:

Visitor pattern vs channel in Go

问题

如果需要生成和处理列表(最好在生成的同时进行处理),惯例是什么?似乎回调函数并不常用,而通道是普遍喜爱的方法。无论是为每个项目提供回调函数还是启动一个goroutine来生成列表并同步读取和处理每个项目,都不会有明显的好处。

如果在等待列表完成时有多个任务需要完成,或者两者都执行昂贵的任务,并且在生成下一个项目时可以处理最后一个项目,我可以理解这种情况。但在这里并非如此。生产者和消费者都是低成本的。

英文:

If there is a list that needs to be generated and processed (ideally, while being generated), what is the convention? It seems like callbacks aren't used as much whereas channels are the universal favorite. There won't be a decisive benefit to either providing a callback to be invoked for each item versus launching a goroutine to generate the list and synchronously reading and processing each item.

I'd understand if there were more than one task to be done while waiting for the list to finish or both were performing expensive tasks and one might be able to work on the last item while the next item is being produced, but that isn't the case, here. Both the producer and consumer are low-cost.

答案1

得分: 3

惯例是使用回调函数。以下是标准库中的几个示例:filepath.Walkast.Walk

使用通道和生成器协程模式的一个缺点是,当消费者在通道关闭之前没有接收到数据时,会泄漏一个协程。另一个问题是可能导致数据竞争。标准库在Go的早期使用了这种模式。由于这些问题,在Go 1之前,这段代码被移除了。

英文:

The convention is to use callbacks. Here are a couple of examples in the standard library: filepath.Walk, ast.Walk.

A drawback of the channel with generator goroutine pattern is that it leaks a goroutine when the consumer does not receive until the channel is closed. Another issue is that creates an opportunity for data races. The standard library used this pattern in the early days of Go. This code was removed before Go 1 because of these issues.

huangapple
  • 本文由 发表于 2016年1月22日 04:13:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/34933416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定