学无先后,达者为师

网站首页 编程语言 正文

无缓冲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

栏目分类
最近更新