Is there a better way to stop an infinite goroutine in Go?
質問
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.
解決
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."