Home >Backend Development >Golang >How to Gracefully Interrupt a TCPListener\'s Accept Goroutine in Go?
Interrupting TCPListener's Accept Goroutine
In Go, servers handling TCP connections create a goroutine to listen for incoming connections using the (*TCPListener).Accept method. When the server needs to be cleanly shut down, this goroutine must be interrupted.
Interruption Method
The way to interrupt the (*TCPListener).Accept goroutine is to simply close the net.Listener that was obtained from net.Listen(...). This will cause the Accept call to return an error, allowing the goroutine to gracefully exit.
Once the net.Listener is closed, the Accept goroutine should return from its execution. This is because the documentation for Accept states that it "waits for the next call and returns a generic Conn". When the net.Listener is closed, there will be no more connections to accept, so the Accept goroutine will exit.
The above is the detailed content of How to Gracefully Interrupt a TCPListener\'s Accept Goroutine in Go?. For more information, please follow other related articles on the PHP Chinese website!