聊聊gost的GoUnterminated

本文主要研究一下gost的GoUnterminatedgit

GoUnterminated

gost/runtime/goroutine.gogithub

// 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.goui

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)的時候會一直遞歸循環下去。atom

doc

相關文章
相關標籤/搜索