Home  >  Article  >  Backend Development  >  Why docall uses gopanic in singleflight?

Why docall uses gopanic in singleflight?

WBOY
WBOYforward
2024-02-08 22:50:21954browse

为什么 docall 在 singleflight 中使用 gopanic?

php editor Banana will answer for you: Why does docall use gopanic in singleflight? In singleflight, when multiple goroutines request the same task at the same time, in order to avoid repeated execution, we need to use the docall function to ensure that only one goroutine executes the task. In order to better handle errors when an error occurs in a goroutine, we use the gopanic function to throw an exception. This can make the error more clear and facilitate us to handle and debug accordingly. Therefore, using gopanic in singleflight can improve the reliability and efficiency of error handling. This is why docall uses gopanic in singleflight.

Question content

I was reading the singleflight source code recently and was confused about 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 gopanic instead of panic directly when using channel? Line 129 uses go docall. In this method, panic occurs and the upper layer cannot recover, so go panic should be meaningless, right?

In addition, if there are concurrent requests and the channel is still not written after the panic, won't other goroutines also block? If anyone is kind enough to read and answer, I would be very grateful~

Understand the design implications

Workaround

gopanic Will cause an unrecoverable panic. After panicking and select make sure the panicked goroutine appears in the stack dump, so you can look at the stack dump and realize something happened that shouldn't happen.

This is just a way to make sure you don't inadvertently recover from something you shouldn't.

The above is the detailed content of Why docall uses gopanic in singleflight?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete