Home  >  Article  >  Backend Development  >  Golang: Why do I still receive messages from the channel after the timer has stopped

Golang: Why do I still receive messages from the channel after the timer has stopped

PHPz
PHPzforward
2024-02-09 23:36:091174browse

Golang: Why do I still receive messages from the channel after the timer has stopped

Golang: Why am I still receiving messages from the channel after the timer has stopped? This is a problem that many Golang developers often encounter when using timers. Timer is a commonly used tool in Golang, which is used to perform specific operations after a certain period of time. However, sometimes even if we explicitly stop the timer, we still receive messages from the channel. What exactly causes this to happen? In this article, PHP editor Zimo will answer this question in detail and provide corresponding solutions.

Question content

The first code (exception):

var ti time.timer
func init() {
    ti = *time.newtimer(3 * time.second)
}
func main() {
    ti.stop()
    t := <-ti.c
    fmt.println("end", t) 
}

Second code (normal):

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

I don't understand why the first code still gets messages from the timer channel after stopping. I don't think this is normal as it seems to render the timer useless.

The second code is normal, the difference is "var ti time.timer" and "var ti *time.timer", one is a value and the other is a pointer.

I'm not familiar with pointers, can anyone help me?

Thanks!

Workaround

You are dereferencing the stock symbol and its value is copied.

This is how to stop:

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

When you copy a timer, &t.r points somewhere else. That's why your timer won't stop.

So you should use *time.ticker instead of time.ticker.

The above is the detailed content of Golang: Why do I still receive messages from the channel after the timer has stopped. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete