#### goroutine泄漏的产生、发现及避免 ####

注意:部分内容摘自 深入探讨 goroutine 泄漏和避免它们的最佳实践 - 知乎

1、goroutine泄漏的产生

// 例1

func newgoroutine(dataChan chan <dataType>) {
     data := makeNetworkCall()
     dataChan <- data // 阻塞住了
     return
}

func main() {
     dataChan := make(chan <dataType>)
     go newgoroutine(dataChan)
     return 
}


// 例2

func newgoroutine(dataChan chan <dataType>) {
     data := <- dataChan // 阻塞住了
     return
}

func main() {
     dataChan := make(chan <dataType>)
     go newgoroutine(dataChan)
     data, err := makeNetworkCall()
     if err != nil {
         return 
     }
     dataChan <- data
     return 
}

2、发现

(1)通过goroutin监控

(2)服务器启动时使用禁用垃圾收集器 debug.SetGCPercent(-1),然后在运行代码中打印 API 启动前和执行后正在运行的 goroutines 的数量,如果服务在前后返回不同数量的 Goroutines,那么该流程中存在泄漏。

func ApplyPromo() {
   fmt.Println(runtime.NumGoroutine())
   defer fmt.Println(runtime.NumGoroutine()
}

3、避免

例如为避免上面两个case,可以将无缓冲区的channel改为有缓冲区的channel。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值