I have a program in which a goroutine executes a long-running computation
that may be canceled. I'm not sure of the best way to do this. I tried
passing the goroutine a "quit" channel that it performs nonblocking
receives on in order to get the message to stop, and I was surprised to
learn that when GOMAXPROCS is 1, the runtime never switches away from the
goroutine to allow another part of the program to actually put something on
that channel. It behaves essentially the same as putting "for { }" in a
goroutine, but in my case it's not an empty or non-communicating loop --
it's doing non-blocking reads.
See http://play.golang.org/p/iZsCXv7vdw for a toy example. The real code
doesn't actually do an infinite loop, just a long computation, but the
result is essentially the same -- I can't stop it.
I know one solution is to call runtime.Gosched() before trying to read from
the channel, but is that the only way? I've read in multiple places people
discouraging the use of this function. Is there another way I should
structure my code? It's possible to just let the goroutine run but ignore
its result, but that would be too inefficient. I actually only want to stop
the goroutine in order to start another one with different inputs. Running
even two at the same time will really slow things down, and if I didn't
stop them before starting new ones I could get several.
Thanks for your help,
-Ryan
--