Memory leaks that may be caused by Golang timer
background
Two days ago, I communicated with a senior Golang; then, he suddenly asked me: Do you know that timer may cause memory leaks?
At that time, I was very confused. After all, I had been testing the Agent I wrote for a long time, but I didn’t find this problem.
Today, I just got to know it.
Let’s talk about the conclusion here:
- Misuse of timer may cause some Goroutines waiting for timer to exit normally, resulting in the resource being unable to be released;
- (ps. Although it is indeed a memory leak, it still feels strange for someone like me who writes C-born)
Next, get to the main topic
Let's look at a piece of code first;
The intention of this code is that the coroutine can continue to execute after the () call and exit;
But what about the actual effect? We did not see any output prompts;
Why then?
The core reason for this is,() This interface was designed to not turn off the Channel since its design;
Since Chan is not closed, the coroutine in this example cannot continue to execute and exits;
package main import ( "time" "fmt" ) func main() { timer := (3 * ) go func() { <- ("Timer has expired.") }() () (60 * ) }
As a repair method:
package main import ( "time" "fmt" ) func main() { timer := (3 * ) go func() { <- ("Timer has expired.") }() //() (0 * ) (60 * ) }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.