dtbiszu7724 2013-05-13 07:35
浏览 698
已采纳

Go软件包syscall conn.Read()是非阻塞的,并导致较高的CPU使用率

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" {
        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, this is causing high CPU usage. How to make conn.Read() a block call?

I've researched into syscall package but got stucked at Syscall.Read() Since I found this issue on my OS X 10.8.3 here is the source code related:

http://golang.org/src/pkg/syscall/zsyscall_darwin_amd64.go?h=Read#L898

I have no idea what Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) means.

  • 写回答

1条回答 默认 最新

  • duanhao1004 2013-05-13 07:40
    关注

    You're not handling TCP correctly. When conn.Read() returns 0 bytes read, that means the peer has closed the TCP connection gracefully. You should probably close your end of the TCP connection in this case.

    (Note that this is not special to Go, read()/recv() returning 0 on a TCP connection more or less universally means the other end has closed the connection)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么