func main() {
rand.Seed(time.Now().Unix())
ctx, cancelFunc := context.WithCancel(context.Background())
anies := make(chan any)
go doSomething(ctx, anies)
intn := rand.Intn(2)
if intn == 0 { //BRANCH1
cancelFunc()
close(anies)
}
time.Sleep(time.Second)
}
func doSomething(ctx context.Context, anies chan any) {
for {
if ctx.Err() == nil { //LINE2
anies <- 1 //LINE3
}
}
}
Can it be possible that somewhen BRANCH1 happens between LINE2 AND LINE3 and I will got panic.
CodePudding user response:
Yes, a panic is possible. Here's an example timeline where a panic occurs. The lines are in increasing time order. The N: prefix represents the goroutine.
1: start goroutine 2
2: call ctx.Err(), it returns nil
1: call cancelFunc()
1: close channel anies
2: send to channel anies. panic because channel is closed.