gpt4 book ai didi

go - 当我不需要停止时,time.Tick 会导致内存泄漏吗?

转载 作者:行者123 更新时间:2023-12-05 01:28:47 33 4
gpt4 key购买 nike

考虑以下代码:

go func() {
for now := range time.Tick(time.Minute) {
fmt.Println(now, statusUpdate())
}
}()

我需要 for 循环永远运行并且永远不需要停止它。会不会导致内存泄漏?

我知道如果我需要中断 for 循环,它会导致内存泄漏。但是,如果我不需要中断 for 循环怎么办?

The doc says

While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks".

我只想做对。

最佳答案

首先,让我们看看“内存泄漏”的定义,来自 Wikipedia :

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released.

重要的是要注意,在您引用的文档中,它没有具体提到“内存泄漏”,只是“泄漏”(意思是“资源泄漏”)。有问题的资源不仅是 ticker 使用的内存,还有运行它的 goroutine。因此,我会将此定义解释为更广泛地适用于“资源泄漏”。

如您引用的文档所述,time.Tick 无法释放自动收报机的资源。

因此根据这个定义,如果在程序的任何后续点不再需要代码,那么就会发生资源泄漏。如果代码在创建后程序的其余部分始终需要,则这不是泄漏。

但是,在维基百科的定义中,还有这个注释:

A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

同样,time.Tick 无法释放自动收报机的资源。

因此根据这个继续定义,您可能会说 time.Tick 的使用始终是资源泄漏。

在实践中,只要您range time.Tick 没有breaking,您就有理由保证代码是将继续用于程序的其余部分,并且不会有“泄漏”。如果您对代码是否会永远使用有任何疑问,请使用 time.NewTicker。和 Stop() 适本地:

go func() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()

for now := range ticker.C {
fmt.Println(now, statusUpdate())
// some exception
if (something) {
break
}
}
}()

关于go - 当我不需要停止时,time.Tick 会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68289916/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com