Home >Backend Development >Golang >Is there a possibility of panic here?
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 } } }
Is it possible that I will panic when branch1 happens between line2 and line3.
Yes, panic is possible. Below is an example of a timeline where a panic occurs. The rows are arranged in ascending order of time. N: prefix stands for goroutine.
1: Start coroutine 2
2: Call ctx.Err(), it returns nil
1: Call cancelFunc()
1: Close channel anis
2: Send to aniy channel. Panic because the channel is closed.
The above is the detailed content of Is there a possibility of panic here?. For more information, please follow other related articles on the PHP Chinese website!