聊聊gost的GoUnterminated


本文主要研究一下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(&times, 1) == 2 {
panic(“hello”)
}
},
&wg,
false,
1e8,
)
wg.Wait()
assert.True(t, atomic.LoadUint64(&times) == 3)

GoUnterminated(func() {
    atomic.AddUint64(&times, 1)
},
    nil,
    false,
    1e8,
)
time.Sleep(1e9)
assert.True(t, atomic.LoadUint64(&times) == 4)

}
这里模拟了一下handler在times为1的时候产生panic,以及handler不产生panic就立刻结束的场景
小结
gost提供了GoSafely方法,该方法提供handle、WaitGroup、ignoreRecover、period参数,其内部使用的是GoSafely,只是catchFunc是内置的;catchFunc对于period大于0的会sleep一下,之后还是执行GoUnterminated,这样子在handle出错(panic)的时候会一直递归循环下去。

添加链接描述
添加链接描述
添加链接描述
添加链接描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值