GOLANG中time.After释放的问题
原文:https://gocn.io/article/403 在谢大群里看到有同学在讨论 // After waits for the duration to elapse and then sends the current time
// on the returned channel.
// It is equivalent to NewTimer(d).C.
// The underlying Timer is not recovered by the garbage collector
// until the timer fires. If efficiency is a concern,use NewTimer
// instead and call Timer.Stop if the timer is no longer needed.
func After(d Duration) <-chan Time {
return NewTimer(d).C
}
提到了一句 package main
import "time"
func main() {
for {
<- time.After(10 * time.Nanosecond)
}
}
显示内存稳定在5.3MB,CPU为161%,肯定被GC回收了的。当然如果放在goroutine也是没有问题的,一样会回收: package main
import "time"
func main() {
for i := 0; i < 100; i++ {
go func(){
for {
<- time.After(10 * time.Nanosecond)
}
}()
}
time.Sleep(1 * time.Hour)
}
只是资源消耗会多一点,CPU为422%,内存占用6.4MB。因此:
那么API所说的 select { case time.After(3*time.Second): return errTimeout case packet := packetChannel: // process packet. }
如果packet非常多,那么总是会走到下面的分支,上面的timer不会立刻释放而是在3秒后才能释放,和下面代码一样: package main
import "time"
func main() {
for {
select {
case <-time.After(3 * time.Second):
default:
}
}
}
这个时候,就相当于会堆积了3秒的timer没有释放而已,会不断的新建和释放timer,内存会稳定在2.8GB,这个当然就不是最好的了,可以主动释放: package main
import "time"
func main() {
for {
t := time.NewTimer(3*time.Second)
select {
case <- t.C:
default:
t.Stop()
}
}
}
这样就不会占用2.8GB内存了,只有5MB左右。因此,总结下这个After的说明:
交作业。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |