不会,defer 就是这样设计的,只有在调用 defer 的 goroutine 中 panic 才会执行,其他 goroutine 没有提及,那么就是没有保证。
文档在
https://golang.org/ref/spec#Defer_statementsA "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.
文档指明了在“the corresponding goroutine” panic 的时候才会 defer 。
为了确定 panic 在一个 goroutine 中的行为,文档也描述了,在
https://golang.org/ref/spec#Handling_panics,我把它贴过来While executing a function F, an explicit call to panic or a run-time panic terminates the execution of F. Any functions deferred by F are then executed as usual. Next, any deferred functions run by F's caller are run, and so on up to any deferred by the top-level function in the executing goroutine. At that point, the program is terminated and the error condition is reported, including the value of the argument to panic. This termination sequence is called panicking.
注意到"in the executing goroutine"的限制,那么就是说 panic 会触发在它所运行的 goroutine 中调用链上的 defer,然后整个程序就退出了。所以 panic 不会管其他 goroutine 中的 defer 。