How to wait until buffered channel (semaphore) is empty?

前端 未结 4 1887
遥遥无期
遥遥无期 2020-12-19 02:36

I have a slice of integers, which are manipulated concurrently:

ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

I\'m using a buffered channel

4条回答
  •  遥遥无期
    2020-12-19 03:16

    You can wait your "sub-goroutines" with the current goroutine in a for loop

    semLimit := 2
    sem := make(chan struct{}, semLimit)
    
    for _, i := range ints {
      // acquire semaphore
      sem <- struct{}{}
    
      // start long running go routine
      go func(id int, sem chan struct{}) {
        // do something
    
        // release semaphore
        <- sem
      }(i, sem)
    }
    
    // wait semaphore
    for i := 0; i < semLimit; i++ { 
      wg<-struct{}{} 
    }
    
    

    Optionnaly it is also possible to program a minimalistic "semaphored waitgroup" with the economy of import sync

    semLimit := 2
    // mini semaphored waitgroup 
    wg := make(chan struct{}, semLimit)
    // mini methods
    wgAdd := func(){ wg<-struct{}{} }
    wgDone := func(){ <-wg }
    wgWait := func(){ for i := 0; i < semLimit; i++ { wgAdd() } }
    
    for _, i := range ints {
      // acquire semaphore
      wgAdd()
    
      // start long running go routine
      go func(id int, sem chan struct{}) {
        // do something
    
        // release semaphore
        wgDone()
      }(i, sem)
    }
    
    // wait semaphore
    wgWait()
    

提交回复
热议问题