日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

無緩沖channel的內存泄漏問題

作者:傅里葉、 更新時間: 2022-07-03 編程語言

無緩沖channel的內存泄漏問題:無緩沖channel在go程里done <- hardWork(job)時,如果外層執行完了后,done <- hardWork(job)寫操作<- 會一直阻塞

func requestWork(ctx context.Context, job interface{}) error {
    ctx, cancel := context.WithTimeout(ctx, time.Second*2)
    defer cancel()

    done := make(chan error)
    go func() {
        done <- hardWork(job)
    }()

    select {
    case err := <-done:
        return err
    case <-ctx.Done():
        return ctx.Err()
    }
}

func main() {
    const total = 1000
    var wg sync.WaitGroup
    wg.Add(total)
    now := time.Now()
    for i := 0; i < total; i++ {
        go func() {
            defer wg.Done()
            requestWork(context.Background(), "any")
        }()
    }
    wg.Wait()
    fmt.Println("elapsed:", time.Since(now))
    time.Sleep(time.Minute*2)
    fmt.Println("number of goroutines:", runtime.NumGoroutine())
}

? go run timeout.go
elapsed: 2.005725931s
number of goroutines: 1001

原文鏈接:https://blog.csdn.net/qq_34562093/article/details/122180380

欄目分類
最近更新