networking - Go package syscall conn.Read() is non-blocking and cause high CPU usage -
strangely, in case read()
non-blocking , caused high cpu usage.
my code:
in function main
:
l, err := net.listen("tcp", ":13798") if err != nil { log.fatal(err) } { // wait connection. conn, err := l.accept() if err != nil { log.fatal(err) } // handle connection in new goroutine. // loop returns accepting, // multiple connections may served concurrently. go reqhandler.tcphandler(conn) runtime.gosched() }
function tcphandler
:
func tcphandler(conn net.conn) { request := make([]byte, 4096) { read_len, err := conn.read(request) if err != nil { if err.error() == "use of closed network 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 { // } request := make([]byte, 4096) } }
the problem is, conn.read()
non-blocking, every time goes log("nothing read")
continue, causing high cpu usage. how make conn.read()
block call?
i've researched syscall
package got stucked @ syscall.read()
since found issue on os x 10.8.3 here source code related:
http://golang.org/src/pkg/syscall/zsyscall_darwin_amd64.go?h=read#l898
i have no idea syscall(sys_read, uintptr(fd), uintptr(_p0), uintptr(len(p)))
means.
you're not handling tcp correctly. when conn.read() returns 0 bytes read, means peer has closed tcp connection gracefully. should close end of tcp connection in case.
(note not special go, read()/recv() returning 0 on tcp connection more or less universally means other end has closed connection)
Comments
Post a Comment