Skip to content

Instantly share code, notes, and snippets.

@soh335
Created January 25, 2017 06:07
Show Gist options
  • Save soh335/48ad889d8919adc2621fd933fa77a19f to your computer and use it in GitHub Desktop.
Save soh335/48ad889d8919adc2621fd933fa77a19f to your computer and use it in GitHub Desktop.
package shutdown
import (
"context"
"sync"
)
type Shutdown struct {
cancel context.CancelFunc
wg sync.WaitGroup
once sync.Once
err error
}
func WithContext(ctx context.Context) (*Shutdown, context.Context) {
ctx, cancel := context.WithCancel(ctx)
return &Shutdown{cancel: cancel}, ctx
}
func (s *Shutdown) Wait() {
s.wg.Wait()
}
func (s *Shutdown) Go(f func()) {
s.wg.Add(1)
go func() {
defer s.wg.Done()
f()
s.once.Do(func() {
s.cancel()
})
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment