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 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行