golang concurrent channel using sync.WaitGroup ensure that all coroutine end and handle the extra business

Problem Description

If a request is http many array id, server id to get the array to perform business, but this business a long time to teach executed, certainly can not execute cycle, multi-let golang coroutine play a role, but I think for some the result id returned by special treatment, must ensure that all coroutine have finished the race in order to return a result, I find the id into the channel and then to spend more coroutine idea is correct, but to ensure that all coroutine precise run complete with sync.WaitGroup quite right, maybe there's a better way, but this is what I want ideas.

Code

package main

import (
   "fmt"
   "sync"
)

func main() {
   var ch chan int = make(chan int,10)
   var wg sync.WaitGroup
   var balance = [...]int{1,2,3,4,5,6,7,8,9}
    j := 0

   for m:=0;m< len(balance);m++{
      ch <- balance[m]
        wg.Add(1)
   }
   for n:=0;n< len(balance);n++  {
      go func() {
      s := <- ch
        fmt.Println("s ",s)
      if s==4||s==7 {
         j++
      }
      defer wg.Done()
      }()
   }
    wg.Wait()
   fmt.Println("j ",j)
   fmt.Println("执行完毕")
}

Each of the channel value is thrown into a wg.Add (1), then the value of each channel will be consumed defer wg.Done (), until it is 0, wg.Wait () does not represent all the waiting operation coroutine ended.
Thus in the final surface will be printed j is 2, the result is correct, of course, just a simple j ++ business operations, where any service logic can fill.

Published 169 original articles · won praise 224 · views 260 000 +

Guess you like

Origin blog.csdn.net/sureSand/article/details/86158066