doumalu9257 2019-03-26 22:43
浏览 392

选择循环的Golang消耗了100%的CPU

I have a resource that needs to be loaded before any access is allowed to it. It also needs to be updated every minute.

The channels are of length 1 struct{}, so the loop will be blocked if the resource has not been loaded.

This code below started to use 100% of my cpu, I tried adding

time.Sleep(10 * time.Millisecond)

Which made the application cpu consumption drop to 1%

I am thinking a ticker would be a better option for the timed collection.

Any ideas why it would consume 100% cpu or any better ideas for implemention?

func (al *AsyncLoop) Run() {
    go func() {
        for {
            select {
            case <-al.chanFetchRequest:
                if al.fetched == false {
                    al.fetchData()
                } else if al.lastUpdated.Add(1*time.Minute).Unix() < time.Now().Unix() && al.fetching == false {
                    go al.fetchData()
                }
                al.chanFetchResponse <- struct{}{}
                continue
            default:
                continue
            }
        }
    }()
}
  • 写回答

1条回答 默认 最新

  • dongshetao1814 2019-03-26 23:07
    关注

    I think you just post to al.chanFetchRequest when there is new data so I think you have to keep reading from this channel all the time. Adding a ticker to the select might cause you to fetch the data even if it has not changed or (worse) before it has even loaded. Why not, in the normal case, take the time whenever you fetch the data then the next time make sure you have waited enough time before fetching again. Something like this:

            var nextFetch time.Time
            for {
                select {
                case <-al.chanFetchRequest:
                    if al.fetched == false {
                        al.fetchData()
                        nextFetch = time.Now().Add(1 * time.Minute)
                    } else if time.Now().After(nextFetch) {
                        al.fetchData()
                        nextFetch = time.Now().Add(1 * time.Minute)
                    }
                    al.chanFetchResponse <- struct{}{}
                }
            }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?