Source File
supervisor.go
Belonging Package
github.com/gotd/td/internal/tdsync
package tdsync
import (
)
// Supervisor is simple task group primitive to control multiple
// long-live tasks.
// Unlike Groups, Supervisor does not cancel when one task is failed.
// Unlike WaitGroup and errgroup.Group this is not allowed to use zero value.
type Supervisor struct {
wg sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
onError func(err error)
}
// NewSupervisor creates new Supervisor.
func ( context.Context) *Supervisor {
, := context.WithCancel()
return &Supervisor{
ctx: ,
cancel: ,
}
}
// WithErrorHandler sets tasks error handler
// Must be called before any Go calls.
func ( *Supervisor) ( func( error)) *Supervisor {
.onError =
return
}
// Go calls the given function in a new goroutine.
func ( *Supervisor) ( func( context.Context) error) {
.wg.Add(1)
go func() {
defer .wg.Done()
if := (.ctx); != nil {
if .onError != nil {
.onError()
}
}
}()
}
// Cancel cancels all goroutines in group.
//
// Note: context cancellation error can be returned by Wait().
func ( *Supervisor) () {
.cancel()
}
// Wait blocks until all function calls from the Go method have returned, then
// returns the first non-nil error (if any) from them.
func ( *Supervisor) () error {
.wg.Wait()
return nil
}
The pages are generated with Golds v0.6.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |