title: How to coordinate shutdown with many goroutines
body: <p>Say I have a function</p>
  
  <pre><code>type Foo struct {}
  
  func (a *Foo) Bar() {
      // some expensive work - does some calls to redis
  }
  </code></pre>
  
  <p>which gets executed within a goroutine at some point in my app. Lots of these may be executing at any given point. Prior to application termination, I would like to ensure all remaining goroutines have finished their work.</p>
  
  <p>Can I do something like this:</p>
  
  <pre><code>type Foo struct {
      wg sync.WaitGroup
  }
  
  func (a *Foo) Close() {
      a.wg.Wait()
  }
  
  func (a *Foo) Bar() {
      a.wg.Add(1)
      defer a.wg.Done()
  
      // some expensive work - does some calls to redis
  }
  </code></pre>
  
  <p>Assuming here that Bar gets executed within a goroutine and many of these may be running at a given time and that Bar should not be called once Close is called and Close is called upon a sigterm or sigint.</p>
  
  <p>Does this make sense?</p>
  
  <p>Usually I would see the Bar function look like this:</p>
  
  <pre><code>func (a *Foo) Bar() {
      a.wg.Add(1)
  
      go func() {
          defer a.wg.Done()
          // some expensive work - does some calls to redis
      }()
  }
  </code></pre>