停止一个计时器会结束 goroutine 吗?

huangapple go评论72阅读模式
英文:

Does stopping a timer end the goroutine?

问题

下面的代码中,通过停止计时器来停止的这样一个简单的 goroutine,会变得干净吗?还是会一直保留在内存中直到程序结束?

go func() {
    <-timer1.C // 在触发之前会被停止。
    fmt.Println("Timer 1 fired")
}()

这段代码中的 goroutine 会在计时器触发之前被停止,因此它不会一直保留在内存中。一旦计时器被停止,goroutine 将被垃圾回收机制清理,并释放相关的资源。

英文:

Does a simple goroutine like the below code that is stopped by stopping a timer become clean? Or stay in memory until the end of the program?

go func() {
    &lt;-timer1.C //Will stop before firing.
    fmt.Println(&quot;Timer 1 fired&quot;)
}()

答案1

得分: 4

如果通道关闭,Go协程将退出。如果通道保持打开状态但从未发送任何内容,则Go协程将永远"挂起",直到程序退出。

如果timer1是一个time.Timer,那么根据文档说明,Stop方法不会关闭通道。文档链接:https://pkg.go.dev/time#Timer.Stop

英文:

If the channel is closed, the Go routine will exit. If the channel remains open but nothing is ever sent over it, then the Go routine will "hang" forever, until the program exits.

If timer1 is a time.Timer, then Stop will not close the channel, as explained in the documentation: https://pkg.go.dev/time#Timer.Stop

huangapple
  • 本文由 发表于 2021年9月8日 21:13:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/69103768.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定