如何使用goroutine游泳池

tld*_*ldr 30 go threadpool goroutine

我想用Go从Yahoo finance下载股票价格电子表格.我将为自己的goroutine中的每个股票发出http请求.我有一个大约2500个符号的列表,但不是并行地发出2500个请求,我宁愿一次做250个.在Java中,我创建了一个线程池,并在它们获得空闲时重用它们.我试图找到类似的东西,一个goroutine池,如果你愿意,但无法找到任何资源.如果有人能告诉我如何完成手头的任务或者为我指出相同的资源,我会很感激.谢谢!

Ros*_*nko 48

我想,最简单的方法是创建250个goroutines并传递一个通道,您可以使用该通道将主goroutine链接传递给子节点,并监听该通道.

当所有链接都传递给goroutines时,你关闭一个频道,所有goroutine就完成了他们的工作.

为了保护自己免受主要goroutine的影响,在孩子处理数据之前完成,你可以使用sync.WaitGroup.

这里有一些代码来说明(不是最终的工作版本,但显示了这一点),我在上面说过:

func worker(linkChan chan string, wg *sync.WaitGroup) {
   // Decreasing internal counter for wait-group as soon as goroutine finishes
   defer wg.Done()

   for url := range linkChan {
     // Analyze value and do the job here
   }
}

func main() {
    lCh := make(chan string)
    wg := new(sync.WaitGroup)

    // Adding routines to workgroup and running then
    for i := 0; i < 250; i++ {
        wg.Add(1)
        go worker(lCh, wg)
    }

    // Processing all links by spreading them to `free` goroutines
    for _, link := range yourLinksSlice {
        lCh <- link
    }

    // Closing channel (waiting in goroutines won't continue any more)
    close(lCh)

    // Waiting for all goroutines to finish (otherwise they die as main routine dies)
    wg.Wait()
}
Run Code Online (Sandbox Code Playgroud)

  • 以下是对此代码的小规模测试:http://play.golang.org/p/fruJiGBWjn (4认同)