title: Wait for concurrent workers to finish before exiting
body: <p>The following code has an obvious problem: the program will exit before all the work is finished by the workers.</p>
  <p>Goroutines of the workers are launched before the sender starts sending data, which must remain.  Starting these goroutines from the sender function is not an option.  It would be easy to do so, however, need to learn a more complex synchronization technique.</p>
  <p>What would be the correct way to wait for the workers to finish?</p>
  <p>Have tried closing the <code>worker1CH</code> and <code>worker2CH</code> channels, as well as adding dedicated sync.WaitGroups to each worker.</p>
  <pre><code>package main
  
  import (
      &quot;log&quot;
      &quot;math/rand&quot;
      &quot;sync&quot;
  )
  
  func main() {
  
      worker1CH := make(chan int, 1)
      worker2CH := make(chan int, 1)
  
      // worker for even numbers
      go func(in chan int) {
          for i := range in {
              log.Print(i)
          }
      }(worker1CH)
  
      // worker for odd numbers
      go func(in chan int) {
          for i := range in {
              log.Print(i)
          }
      }(worker2CH)
  
      // sender which sends even numbers to worker1CH, and odd numbers to worker2CH
      var wg sync.WaitGroup
      wg.Add(1)
      go func(wg *sync.WaitGroup, evenChan chan int, oddChan chan int) {
          defer wg.Done()
  
          data := rand.Perm(10)
          for _, i := range data {
              switch i%2 {
              case 0:
                  evenChan &lt;- i
              default:
                  oddChan &lt;- i
              }
          }
      }(&amp;wg, worker1CH, worker2CH)
      wg.Wait()
  
  }
  </code></pre>