这种功能是否可能导致goroutine泄漏

时间:2017-09-14 09:11:18

标签: 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()
    }
}

嗨,我上面写了一个函数,想知道是否有可能导致goroutine泄漏。

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

2 个答案:

答案 0 :(得分:1)

我不能每次都复制这种行为,但可能会有些泄漏。如果doSomething做了一些繁重的计算,同时goroutine在intervalChan <- true上被阻止,因为它无法进入频道。在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)
}

答案 1 :(得分:1)

你的第一个goroutine无限期被阻止的唯一地方是intervalChan <- true。将它放在另一个选择块中以便能够取消发送:

go func() {
    for {
        select {
        case <-ctx.Done():
            return
        case <-time.After(time.Second * time.Duration(intervalTime)):
            select {
            case <-ctx.Done():
                return
            case intervalChan <- true:
            }
        }
    }
}()
相关问题