我有一个 go 服务,它在
main.go
中初始化一个缓冲通道。我正在使用它来控制在我的一个函数中同时生成的 goroutine 的最大数量。我的代码看起来类似于下面给出的代码
func main() {
guardChannel := make(chan struct{}, 20)
waitgroup = new(sync.WaitGroup)
service := &mypackage.Processor{
// Some other dependencies
Controller: guardChannel,
WaitGroup: waitgroup
}
ConfgiureEndPoints(service) // Sets up the API endpoints
}
// Triggered by an API
func(s *service) myProcess(ids []int{}) {
for _, id := range ids {
s.Controller <- struct{}{}
go func(id int) {
s.triggerProcess(id)
<- s.Controller
}(id)
}
}
func(s *service) triggerProcess(id) {
s.waitgroup.Add(1)
defer s.waitgroup.Done()
// Continue process
}
据我测试,这工作正常。但我最近读到here,当一个频道不被使用时,它会被垃圾收集。
在这里,我的API不会被频繁触发。它每小时只会触发两次。每次,它将有大约 50 个条目要处理,最多只需几秒钟即可完成。所以简而言之,我的频道大部分时间都是空的。在那种情况下,一旦通道在一段时间后收集垃圾,它会停止工作吗?发生这种情况需要多长时间?
service
变量保留对通道的引用,因此在不再引用service
变量并且没有goroutines引用通道之前,它不会被垃圾收集。因此,通道被垃圾收集在这里不是问题。