簡體   English   中英

如何檢測goroutine泄漏?

[英]How to detect goroutine leaks?

在下面的代碼中:

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) ),如果主 goroutine 未准備好接收,則由於發送阻塞( ch <- "paper" )導致 go-routine 泄漏。

使用緩沖通道ch := make(chan string, 1)不會阻塞 send( ch <- "paper" )

如何檢測這種 go​​-routine 泄漏?

有一些軟件包可以讓你做到這一點。 我過去用過的兩個:

通常,他們使用runtime包中的功能在代碼運行前后檢查堆棧並報告可疑的泄漏。 建議在測試中使用它們。 我發現這在實踐中效果很好,並在幾個項目中使用了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM