Strangely, in my case Read() is non-blocking and caused high CPU usage.
My code:
In function main:
l, err := net.Listen("tcp", ":13798")
if err != nil {
log.Fatal(err)
}
for {
// Wait for a connection.
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
// Handle the connection in a new goroutine.
// The loop then returns to accepting, so that
// multiple connections may be served concurrently.
go reqHandler.TCPHandler(conn)
runtime.Gosched()
}
Function TCPHandler:
func TCPHandler(conn net.Conn) {
request := make([]byte, 4096)
for {
read_len, err := conn.Read(request)
if err != nil {
if err.Error() == "use of closed network connection" { // TODO: Hack way, this happens when high-level logic meets an error and closed connection.
LOG("Conn closed, error might happened)
break
}
neterr, ok := err.(net.Error);
if ok && neterr.Timeout() {
fmt.Println(neterr)
LOG("Client timeout!")
break
}
}
if read_len == 0 {
LOG("Nothing read")
continue
} else {
// do something
}
request := make([]byte, 4096)
}
}
The problem is, conn.Read is non-blocking, so every time it goes to "LOG("Nothing read")" then continue, so it's causing high CPU usage. How to make conn.Read a block call?
Best regards,
Shuaiying Hou