简体   繁体   English

如何检测goroutine泄漏?

[英]How to detect goroutine leaks?

In the below code:在下面的代码中:

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()
}

Because of unbuffered channel( ch := make(chan string) ), go-routine leaks due to block on send( ch <- "paper" ), if main goroutine is not ready to receive.由于无缓冲通道( ch := make(chan string) ),如果主 goroutine 未准备好接收,则由于发送阻塞( ch <- "paper" )导致 go-routine 泄漏。

Using buffered channel ch := make(chan string, 1) does not block send( ch <- "paper" )使用缓冲通道ch := make(chan string, 1)不会阻塞 send( ch <- "paper" )

How to detect such go-routine leaks?如何检测这种 go​​-routine 泄漏?

There are some packages that let you do that.有一些软件包可以让你做到这一点。 Two that I've used in the past:我过去用过的两个:

Generally, they use functionality from the runtime package to examine the stack before and after your code runs and report suspected leaks.通常,他们使用runtime包中的功能在代码运行前后检查堆栈并报告可疑的泄漏。 It's recommended to use them in tests.建议在测试中使用它们。 I found this works well in practice and used it in a couple of projects.我发现这在实践中效果很好,并在几个项目中使用了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM