dp0518 2018-03-28 17:18
浏览 89
已采纳

Golang stdin循环上的CPU使用率过高

I have a golang app which needs to listen for input on stdin - not as a command line utility but to keep running and listening. The following code, slightly edited down, works but has very high CPU load when 'idle' - and I am not sure why - nor clear how this could be done better. So I need the same functionality without the CPU load! (this is part of an authentication handler for ejabberd)

bioIn := bufio.NewReader(os.Stdin)
bioOut := bufio.NewWriter(os.Stdout)

var err error
var success bool
var length uint16
var result uint16

for {
    binary.Read(bioIn, binary.BigEndian, &length)

    buf := make([]byte, length)

    r, _ := bioIn.Read(buf)
    if r == 0 {
        continue
    }

    if err == nil {
        data := strings.Split(string(buf), ":")
        // I have code to handle the incoming data here...
    } else {
        success = false
    }

    length = 2
    binary.Write(bioOut, binary.BigEndian, &length)

    if success != true {
        result = 0
    } else {
        result = 1
    }

    binary.Write(bioOut, binary.BigEndian, &result)
    bioOut.Flush()
}

ANSWER:

I added a short sleep as suggested and this has worked a charm; didn't need to be long and no noticeable impact on the authentication the service is providing. With the reassurance incoming data is buffered this is perfect fix. Thanks all.

r, _ := bioIn.Read(buf)
    if r == 0 {
        time.Sleep(25 * time.Millisecond)
        continue
}
  • 写回答

2条回答 默认 最新

  • douhu8851 2018-03-28 17:48
    关注

    You have a tight infinite loop, which will always take as much CPU as the OS will allow. You are always checking to see if there's any input and (in your sample code) you never wait for new input - you just continuously poll stdin to see if there is any. You should probably use time.Sleep() to wait some time between each check.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?