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/