为什么docall在singleflight中使用go panic?

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

Why does docall use go panic in singleflight?

问题

我最近在阅读singleflight的源代码,对于line 158感到困惑。

if len(c.chans) > 0 {
	go panic(e)
	select {} // Keep this goroutine around so that it will appear in the crash dump.
} else {
	panic(e)
}

为什么在使用通道时要使用go panic而不是直接使用panic?在line 129中使用go docall,在该方法中发生panic,上层无法恢复,所以go panic应该是没有意义的,对吗?

此外,如果存在并发请求,在发生panic后通道仍未写入,其他goroutine也不会阻塞吗?如果有人能够给出解答,我将非常感激~

了解设计的含义

英文:

I was recently reading the singleflight source code and I was puzzled by line 158.

if len(c.chans) > 0 {
	go panic(e)
	select {} // Keep this goroutine around so that it will appear in the crash dump.
} else {
	panic(e)
}

Why use go panic instead of direct panic when using channel? Use go docall on line 129, panic in this method, the upper layer cannot recover, so go panic should be meaningless, right?

Furthermore, if there are concurrent requests, the channel is still not written after the panic, won't other goroutines also block? If someone with good intentions reads and answers, I am very grateful~

Understand design implications

答案1

得分: 4

go panic会导致一个无法恢复的恐慌。恐慌和之后的select确保恐慌的goroutine出现在堆栈转储中,这样你可以查看堆栈转储并意识到发生了本不应该发生的情况。

这只是一种确保你不会意外地从不应该恢复的情况中恢复的方法。

英文:

go panic will result in a panic that cannot be recovered from. The panic and the select after it ensures that the panicking goroutine appears in the stack dump, so you can look at the stack dump and realize that a situation that should not have happened has happened.

This is simply a way to ensure that you do not unintentionally recover from something that should not be recovered from.

huangapple
  • 本文由 发表于 2023年5月9日 00:07:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76202350.html
匿名

发表评论

匿名网友

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

确定