聊聊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)的时候会一直递归循环下去。

doc

  • gost

本文来自:Segmentfault

感谢作者:codecraft

查看原文:聊聊gost的GoUnterminated

相关阅读 >>

聊聊dubbo-Go-proxy的consulregistryload

Golang实战群:日志的处理机制

Golang 编码转换解决方案

Golang遇到高并发秒杀~

手撸Golang 行为型设计模式 访问者模式

Go语言向函数传递数组

关于Golang-import导入包语法

2021-04-19

[系列] - Go-gin-api 规划目录和参数验证(二)

Go学习六·集合(map)

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...