代码之家  ›  专栏  ›  技术社区  ›  overexchange

如何检测日常泄漏?

  •  0
  • overexchange  · 技术社区  · 4 年前

    在下面的代码中:

    package main
    
    import (
        "context"
        "fmt"
        "time"
    )
    
    func cancellation() {
        duration := 150 * time.Millisecond
        ctx, cancel := context.WithTimeout(context.Background(), duration)
        defer cancel()
    
        ch := make(chan string)
    
        go func() {
            time.Sleep(time.Duration(500) * time.Millisecond)
            ch <- "paper"
        }()
    
        select {
        case d := <-ch:
            fmt.Println("work complete", d)
        case <-ctx.Done():
            fmt.Println("work cancelled")
        }
    
        time.Sleep(time.Second)
        fmt.Println("--------------------------------------")
    }
    
    func main() {
        cancellation()
    }
    

    由于无缓冲通道( ch := make(chan string) ),由于发送受阻而导致常规泄漏( ch <- "paper" ),如果主goroutine尚未准备好接收。

    使用缓冲通道 ch := make(chan string, 1) 不阻止发送( ch<-“纸” )

    如何检测此类常规泄漏?

    0 回复  |  直到 4 年前
        1
  •  1
  •   Eli Bendersky    4 年前

    有一些软件包可以让你做到这一点。我过去用过的两个:

    通常,它们使用来自 runtime 包来检查代码运行前后的堆栈,并报告可疑的泄漏。建议在测试中使用它们。我发现这在实践中效果很好,并在几个项目中使用了它。