Golang:为什么在定时器停止后我还会从通道收到消息

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

Golang: Why i also get a message from channel after timer stop

问题

第一段代码(异常):

var ti time.Timer
func init() {
    ti = *time.NewTimer(3 * time.Second)
}
func main() {
    ti.Stop()
    t := <-ti.C
    fmt.Println("End", t) 
}

第二段代码(正常):

var ti *time.Timer
func init() {
    ti = time.NewTimer(3 * time.Second)
}
func main() {
    ti.Stop()
    t := <-ti.C
    fmt.Println("End", t) // 死锁!
}

我无法理解为什么第一段代码在停止计时器后仍然从计时器通道接收消息。我认为这是异常的,因为它似乎使计时器失去了作用。

而第二段代码是正常的,区别在于"var ti time.Timer"和"var ti *time.Timer",一个是值类型,另一个是指针类型。

我对指针不太熟悉,有人可以帮忙吗?

谢谢!

英文:

first code (abnormal):

var ti time.Timer
func init() {
	ti = *time.NewTimer(3 * time.Second)
}
func main() {
	ti.Stop()
	t := &lt;-ti.C
	fmt.Println(&quot;End&quot;, t) 
}

second code (normal):

var ti *time.Timer
func init() {
	ti = time.NewTimer(3 * time.Second)
}
func main() {
	ti.Stop()
	t := &lt;-ti.C
	fmt.Println(&quot;End&quot;, t) // deadlock!
}

I can't understand why fistr code also get msg from timer channel after stop. I think it is abnormal because it seems to make timer lose its role.

And second code is normal ,the different is "var ti time.Timer" and "var ti *time.Timer", one is value and other is pointer.

I'm not familiar with pointer,can someone help me?

thanks!

答案1

得分: 0

你正在取消引用 ticker 并复制了它的值。

这是 Stop 方法:

func (t *Ticker) Stop() {
	stopTimer(&t.r)
}

由于你复制了计时器,&t.r 指向了其他地方。这就是为什么你的计时器没有停止的原因。

所以你应该使用 *time.Ticker 而不是 time.Ticker

英文:

You are dereferencing ticker and its value gets copied.

Here is the Stop method:

func (t *Ticker) Stop() {
	stopTimer(&amp;t.r)
}

As you copied the timer, the &amp;t.r points to somewhere else. That's why your timer doesn't stop.

So you should be using *time.Ticker not time.Ticker.

huangapple
  • 本文由 发表于 2023年2月19日 14:33:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498403.html
匿名

发表评论

匿名网友

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

确定