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

前端 未结 4 1891
遥遥无期
遥遥无期 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:09

    You can't use a semaphore (channel in this case) in that manner. There's no guarantee it won't be empty any point while you are processing values and dispatching more goroutines. That's not a concern in this case specifically since you're dispatching work synchronously, but because there's no race-free way to check a channel's length, there's no primitive to wait for a channel's length to reach 0.

    Use a sync.WaitGroup to wait for all goroutines to complete

    sem := make(chan struct{}, 2)
    
    var wg sync.WaitGroup
    
    for _, i := range ints {
        wg.Add(1)
        // acquire semaphore
        sem <- struct{}{}
        // start long running go routine
        go func(id int) {
            defer wg.Done()
            // do something
            // release semaphore
            <-sem
        }(i)
    }
    
    wg.Wait()
    

提交回复
热议问题