实现说明
Runtime NumGoroutine 协程泄漏观察可以归结为函数 main。
在这里做循环的是 for i := 1; i <= 4; i++。工作交给 goroutine 执行,结果通过 channel 传回,两个执行上下文之间的交接是安全的。函数用 defer 提前登记清理,任何退出路径都不会忘记它。
使用要点
- 跑完文件,输出里会留下标记——
goroutines before:、goroutines while running:、goroutines after join:。
常见问题
运行「Runtime NumGoroutine 协程泄漏观察」会打印什么?
整个文件跑完,输出行以 goroutines before:、goroutines while running:、goroutines after join: 这类前缀开头。
核心语句
started <- struct{}{} // report that this goroutine is live
started := make(chan struct{})
<-started // wait until all four are scheduled before counting
代码示例
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func main() {
// watch for goroutine leaks between phases
fmt.Println("goroutines before:", runtime.NumGoroutine())
var wg sync.WaitGroup
started := make(chan struct{})
for i := 1; i <= 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
started <- struct{}{} // report that this goroutine is live
time.Sleep(5 * time.Millisecond)
}()
}
for i := 0; i < 4; i++ {
<-started // wait until all four are scheduled before counting
}
fmt.Println("goroutines while running:", runtime.NumGoroutine())
wg.Wait()
fmt.Println("goroutines after join:", runtime.NumGoroutine())
}