<分区>
我们有一个生成父 goroutine 的主 go 例程,父 goroutine 又生成一个子 go 例程。
即使在父 goroutine 返回后,子 goroutine 仍然运行。这会导致 goroutine 泄漏。
我们如何避免这种情况?
下面我添加了一个代码片段来模拟以下内容 这里的子 goroutine 可以是任何一个长时间运行的进程,比如数据库查询、api 调用等
Program output:
In main function - 1
Starting parent function - 2
Starting child function - 3
Child timed out - 3
Completed parent - 2 // Implying that child goroutine is still running with main routine
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
// WaitGroup used by main to wait for parent goroutine
var wg sync.WaitGroup
// Long duration process time
var duration = 100
func main() {
fmt.Println("In main function - ", runtime.NumGoroutine())
wg.Add(1)
go parentRoutine()
wg.Wait()
fmt.Println("Completed parent - ", runtime.NumGoroutine())
}
func parentRoutine() {
fmt.Println("Starting parent function - ", runtime.NumGoroutine())
childRes := make(chan int)
// Spawning child goroutine
go func() {
// Here the child is a simulation of a long running process which might take more time than expected timeout. It runs even after parent returns due to timeout
fmt.Println("Starting child function - ", runtime.NumGoroutine())
time.Sleep(time.Duration(duration)*time.Second)
fmt.Println("Child ended - ", runtime.NumGoroutine())
childRes <- 1
}()
select {
case <-childRes:
fmt.Println("Child completed - ", runtime.NumGoroutine())
case <- time.After(time.Duration(3)*time.Second):
fmt.Println("Child timed out - ", runtime.NumGoroutine())
}
wg.Done()
}