英文:
Is there a better way to stop an infinite goroutine in Go?
问题
我使用goroutines制作了一个简单的时钟信号:
func clockloop(ch chan byte) {
count := 0
for {
time.Sleep(FRAMELEN)
count++
innerfor:
for count {
select {
case ch <- 1:
count--
default:
break innerfor
}
}
}
}
func MakeClock() chan byte {
clock := make(chan byte)
go clockloop(clock)
return clock
}
我知道这个时钟不精确,但这并不重要。我想知道的是停止这个goroutine的最佳方法是什么?
理想情况下,我希望它在任何监听该通道的监听器超出范围时立即停止,但我不知道如何做到这一点(就像垃圾收集器一样,但用于goroutines)。我想出了两种手动停止它的方法:(1)使用一个全局停止变量,所有这样的goroutines都会在每个循环中检查它,(2)使用一个停止通道。每种方法的缺点是我必须手动停止goroutines。
英文:
I made a simple clock signal using goroutines:
func clockloop(ch chan byte) {
count := 0
for {
time.Sleep(FRAMELEN)
count++
innerfor:
for count {
select {
case ch <- 1:
count--
default:
break innerfor
}
}
}
}
func MakeClock() chan byte {
clock := make(chan byte)
go clockloop(clock)
return clock
}
I know this clock is imprecise but that is irrelevant. What I want to know is what is the best way to stop this goroutine?
Ideally, I would have liked it to stop as soon as any listeners to the channel go out of scope but I do know how to do that (much like a garbage collector but for goroutines). I have come up with two ways to stop it manually: (1) with a global stop variable that all such goroutines would check every loop and (2) with a stop channel. The disadvantage of each of these is I have to manually stop the goroutines.
答案1
得分: 11
一个停止通道是一个很好的方法来做到这一点。一个goroutine必须自己停止。没有办法从外部杀死一个goroutine。
供参考,这个线程在Go-Nuts上,Ian基本上说了这个,Russ补充说,“杀死单个goroutine是一件非常不稳定的事情:无法知道这些goroutine是否还有需要清理的锁或其他资源,以使程序继续平稳运行。”
英文:
A stop channel is a good way to do it. A goroutine must stop itself. There is no way to externally kill one.
For reference there is this thread on Go-Nuts where Ian says essentially this and Russ adds, "Killing individual goroutines is a very unstable thing to do:
it's impossible to know what locks or other resources those
goroutines had that still needed to be cleaned up for the
program to continue running smoothly."
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论