Golang for-select炸毁CPU

Shi*_*iyu 1 linux multithreading go goroutine ubuntu-16.04

我有一个grpc基准测试代码,该代码使用一个函数使用for-select子句将数百个goroutine通道合并到一个通道。代码是这样的

     func (b *B) merge(
          ctx context.Context,
          nodes ...<-chan *pb.Node,
        ) chan *pb.Node {
    allNodes := make(chan *pb.Node)
    var wg sync.WaitGroup
    wg.Add(len(nodes))
    for _, n := range nodes {
        go func(n <-chan *pb.Node) {
            defer wg.Done()
            for {
                select {
                case <-ctx.Done():
                    return
                case val, ok := <-n:
                    if ok {
                        allNodes <- val
                    }
                }
            }
        }(n)
    }
    go func() {
        wg.Wait()
        close(allNodes)
    }()
    return allNodes
}
Run Code Online (Sandbox Code Playgroud)

当我在ubuntu 16.04中通过top命令监视代码时,我看到2核服务器变得疯狂,超过了CPU使用率的196%。

然后,我使用pprof包分析了我的代码,它说98%的cpu旋转了此函数,并且top函数生成了这样的结果

    flat  flat%   sum%        cum   cum%
   1640ms  5.78%  5.78%    27700ms 97.60%  B (*B).merge.func1
    5560ms 19.59% 25.37%    22130ms 77.98%  runtime.selectgo
     770ms  2.71% 28.08%    11190ms 39.43%  runtime.sellock
    2700ms  9.51% 37.60%    10430ms 36.75%  runtime.lock
    7710ms 27.17% 64.76%     7710ms 27.17%  runtime.procyield
     460ms  1.62% 66.38%     3850ms 13.57%  context.(*cancelCtx).Done
    1210ms  4.26% 70.65%     3350ms 11.80%  runtime.selunlock
    2700ms  9.51% 80.16%     2900ms 10.22%  sync.(*Mutex).Lock
    2110ms  7.43% 87.60%     2140ms  7.54%  runtime.unlock
     360ms  1.27% 88.87%      860ms  3.03%  runtime.typedmemclr
Run Code Online (Sandbox Code Playgroud)

任何人都可以给我一些有关如何编写正确的代码以合并大量通道的建议,似乎这个for-select块只会使cpu疯狂,而在其后面使用procyield并不是一个很有前途的机制?

无论如何,有控制进程的cpu使用率的方法吗?

Adr*_*ian 5

似乎最有可能在nodes取消上下文之前关闭在参数中传递的通道。这会将您的for循环变成紧密循环,这将消耗所有可用的CPU。由于通道一旦关闭就无法重新打开,因此一旦ok错误就可以安全地从goroutine返回,这可以解决该问题:

    go func(n <-chan *pb.Node) {
        defer wg.Done()
        for {
            select {
            case <-ctx.Done():
                return
            case val, ok := <-n:
                if !ok {
                    return
                }
                allNodes <- val
            }
        }
    }(n)
Run Code Online (Sandbox Code Playgroud)