I have 2 goroutines, g
is used to detect the condition when f
should stop, f
checks whether it should stop in each iteration before doing the actual processing. In other languages such as Java, I would use a thread-safe shared variable, like the following code:
func g(stop *bool) {
for {
if check_condition() {
*stop = true
return
}
}
}
func f(stop *bool) {
for {
if *stop {
return
}
do_something()
}
}
func main() {
var stop = false
go g(&stop)
go f(&stop)
...
}
I know the code above is not safe, but if I use channel to send stop from g
to f
, f
would be blocked on reading from the channel, this is what I want to avoid. What is the safe and idiomatic way of doing this in Go?