英文:
Is it possible 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 { //分支1
cancelFunc()
close(anies)
}
time.Sleep(time.Second)
}
func doSomething(ctx context.Context, anies chan any) {
for {
if ctx.Err() == nil { //第2行
anies <- 1 //第3行
}
}
}
是否有可能在第2行和第3行之间发生分支1,并且我会收到 panic 错误?
英文:
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.
答案1
得分: 1
是的,可能会发生恐慌。以下是一个发生恐慌的示例时间线。行按时间顺序递增。N: 前缀表示 goroutine。
1: 启动 goroutine 2
2: 调用 ctx.Err(),返回 nil
1: 调用 cancelFunc()
1: 关闭通道 anies
2: 向通道 anies 发送数据。由于通道已关闭,发生恐慌。
英文:
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<br>
2: call ctx.Err(), it returns nil<br>
1: call cancelFunc()<br>
1: close channel anies<br>
2: send to channel anies. panic because channel is closed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论