无限循环通道操作导致较高的CPU使用率

问题描述 投票:0回答:1

代码示例如下

var TestChan chan int    

func SendDataToChannel(dataIn int){
        select {
           case TestChan <- dataIn:
           return
        default:
          return
    }
}

func HandleChannelData(){

    for{
        time.Sleep(10 * time.Millisecond)
        tmpData := <- TestChan
        /*
        DoSomething with tmpData, call other server
        */
     }
}

func main(){
    TestChan = make(chan int)
    go HandleChannelData()
    /*
        Start server
     */
 }

该情况是,在我的服务器中,每个请求(每3,000 qps)都会调用SendDataToChannnel。 HandleChannelData中的DoSomething需要花费时间来处理,并且其下游处于QPS限制之下,因此我只需在HandleChannelData中添加睡眠即可。添加到Channel的数据应该是非阻塞的,可以丢弃,因此我在此处获得了“选择默认值”和非缓冲Channel。

当服务器运行时,CPU使用率无限增加,最终达到95%(4核),而我必须关闭服务器。我pprof服务器获得火炬图,什么也没找到(在没有此通道逻辑的情况下,同一服务器的分配相同)我对CPU使用率感到困惑。

go cpu channel
1个回答
0
投票

最后,我发现在添加通道逻辑时,该逻辑会将一些数据添加到服务器中其他代码经常对其进行序列化/反序列化的位置。那就是吃CPU的地方。结果,CPU的增加与无限通道逻辑无关]

© www.soinside.com 2019 - 2024. All rights reserved.