How to wait until buffered channel (semaphore) is empty?
<p>I have a slice of integers, which are manipulated concurrently:</p>
<pre><code>ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
</code></pre>
<p>I'm using a buffered channel as semaphore in order to have an upper bound of concurrently running go routines:</p>
<pre><code>sem := make(chan struct{}, 2)

for _, i := range ints {
  // acquire semaphore
  sem &lt;- struct{}{}

  // start long running go routine
  go func(id int, sem chan struct{}) {
    // do something

    // release semaphore
    &lt;- sem
  }(i, sem)
}
</code></pre>
<p>The code above works pretty well until the last or last two integers are reached, because the program ends before those last go routines are finished.</p>
<p><strong>Question</strong>: how do I wait for the buffered channel to drain?</p>