简体   繁体   中英

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.

Using buffered channel ch := make(chan string, 1) does not block send( ch <- "paper" )

How to detect such go-routine leaks?

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. It's recommended to use them in tests. I found this works well in practice and used it in a couple of projects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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