go - 这个函数是否可能导致 goroutine 泄漏

标签 go memory-leaks goroutine

func startTimer(ctx context.Context, intervalTime int) {
    intervalChan := make(chan bool) 
    go func() {
        for {
            select {
            case <-ctx.Done():
                return
            case <-time.After(time.Second * time.Duration(intervalTime)):
                intervalChan <- true
            }
        }
    }()


    for {
        select {
        case <-ctx.Done():
            return
        case <-intervalChan:
            doSomething()
    }
}

你好,我写了一个func,想知道会不会导致goroutine leak。

例如,第一个 select 语句将 true 发送到 intervalChan,然后第二个 select 语句从 ctx.Done() 接收 Done 标志并返回。 goroutine 会永远阻塞吗?

最佳答案

我不能每次都复制这种行为,但可能是一些泄漏。如果doSomething做一些繁重的计算,同时 goroutine 在 intervalChan <- true 上被阻塞因为它不能插入 channel 。在doSomething之后完成执行并且上下文被取消,startTimer 在 goroutine 之前存在,这将导致阻塞的 goroutine,因为没有任何消费者 intervalChan .

go version go1.8.3 darwin/amd64

package main

import (
    "context"
    "fmt"
    "time"
)

func startTimer(ctx context.Context, intervalTime int) {
    intervalChan := make(chan bool)
    go func() {
        for {
            select {
            case <-ctx.Done():
                fmt.Println("Done from inside of goroutine.")
                return
            case <-time.After(time.Second * time.Duration(intervalTime)):
                fmt.Println("Interval reached.")
                intervalChan <- true
            }
        }
    }()

    for {
        select {
        case <-ctx.Done():
            fmt.Println("Done from startTimer.")
            return
        case <-intervalChan:
            time.Sleep(10 * time.Second)
            fmt.Println("Done")
        }
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    startTimer(ctx, 2)
}

关于go - 这个函数是否可能导致 goroutine 泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46214982/

相关文章:

go - 在 Go 中强制使用特定的导入路径

google-app-engine - 如何在 GAE Standard Go 中缩小到 0 个实例

iphone - iOS KeychainItemWrapper 中的内存泄漏

concurrency - 多个 goroutine 打印到标准输出是否安全?

Golang 线正在抛线 : type x does not implement interface error

go - 尝试创建 MovingAvarage 类型的 slice

c++什么时候终止程序的内存泄漏很重要?

c++ - 视觉检漏仪输出分析 : not able to decode what the result on output screen means

go - Go channel 似乎没有受到阻碍,尽管应该是

windows - 简单的 goroutine 不能在 Windows 上工作