Home > Backend Development > Golang > 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
Release: 2024-02-09 23:36:09
forward
1201 people have browsed it

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) 
}
Copy after login

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!
}
Copy after login

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)
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template