It is a race condition. In such situation you need to use WaitGroup.
Using time sleep is dangerous as we cannot predict how go routines are executed by the scheduler.
See the following code:
func main() {
var wait sync.WaitGroup
wait.Add(1);
go func() {
for {
if !value {
value = true
wait.Done()
}
}
}()
wait.Wait()
//time.Sleep(time.Second)
for {
if !value {
panic("FALSE!")
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…