这里可能会出现恐慌吗?

huangapple go评论86阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月4日 15:00:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75343501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定