dthp96899 2015-09-02 13:02
浏览 68
已采纳

Golang:限制阻塞操作的并发级别

I have the following scenario: I am receiving a message on a channel telling me to upload a file. The upload is made by the blocking function uploadToServer. The zipGen channel may receive several messages per second, and I want to upload maximum 5 files simultaneously (not more, but possibly less - depending on how many messages are sent on zipGen by a third worker that is out of the scope of this question).

The listenToZips function runs inside a go routine (go listenToZips() on the file's init function):

func listenToZips() {
    for {
        select {
        case zip := <-zipGen:
          uploadToServer(zip) // this is blocking
        }
    }
}

If I launch go uploadToServer(zip) instead of just uploadToServer(zip) - I get too much concurrency (so for example my program will try to upload 10 files at the same time, but I want a maximum of 5).

On the other hand, without go uploadToServer(zip) (just using uploadToServer(zip) like in the above function), I only upload one file at a time (since the uploadToServer(zip) is blocking).

How can I achieve this level of control to allow me a max upload of 5 files simultaneously?

Thanks!

  • 写回答

2条回答 默认 最新

  • dougou8458 2015-09-02 13:07
    关注

    The simplest option - prespawn N goroutines that take input from the channel, and upload it, in a loop. In each goroutine's context the operation will be blocking, but N goroutines do this. Only one goroutine will receive each message, of course.

    func listenToZips(concurrent int) {
    
        for i:=0; i < concurrent; i++ {
    
          // spawn a listener goroutine
          go func() {
    
             for {
                select {
                case zip := <-zipGen:
                   uploadToServer(zip) // this is blocking
                }
             }
          }()
    
       }
    
    }
    

    Of course you can then add stop condition, probably using a different channel, but the basic idea is just the same.

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

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥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