Created
January 25, 2017 06:07
-
-
Save soh335/48ad889d8919adc2621fd933fa77a19f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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