序
本文次要钻研一下 gost 的 GoUnterminated
GoUnterminated
gost/runtime/goroutine.go
// GoUnterminated is used for which goroutine wanna long live as its process.
// @period: sleep time duration after panic to defeat @handle panic so frequently. if it is not positive,
// the @handle will be invoked asap after panic.
func GoUnterminated(handle func(), wg *sync.WaitGroup, ignoreRecover bool, period time.Duration) {
GoSafely(wg,
ignoreRecover,
handle,
func(r interface{}) {
if period > 0 {time.Sleep(period)
}
GoUnterminated(handle, wg, ignoreRecover, period)
},
)
}
GoUnterminated 办法提供 handle、WaitGroup、ignoreRecover、period 参数,其外部应用的是 GoSafely,只是 catchFunc 是内置的;catchFunc 对于 period 大于 0 的会 sleep 一下,之后还是执行 GoUnterminated,这样子在 handle 出错 (
panic
) 的时候会始终递归循环上来
实例
gost/runtime/goroutine_test.go
func TestGoUnterminated(t *testing.T) {times := uint64(1)
var wg sync.WaitGroup
GoUnterminated(func() {if atomic.AddUint64(×, 1) == 2 {panic("hello")
}
},
&wg,
false,
1e8,
)
wg.Wait()
assert.True(t, atomic.LoadUint64(×) == 3)
GoUnterminated(func() {atomic.AddUint64(×, 1)
},
nil,
false,
1e8,
)
time.Sleep(1e9)
assert.True(t, atomic.LoadUint64(×) == 4)
}
这里模仿了一下 handler 在 times 为 1 的时候产生 panic,以及 handler 不产生 panic 就立即完结的场景
小结
gost 提供了 GoSafely 办法,该办法提供 handle、WaitGroup、ignoreRecover、period 参数,其外部应用的是 GoSafely,只是 catchFunc 是内置的;catchFunc 对于 period 大于 0 的会 sleep 一下,之后还是执行 GoUnterminated,这样子在 handle 出错 (panic
) 的时候会始终递归循环上来。
doc
- gost