Skip to content

Commit

Permalink
runctx: allow to start group without notify signals
Browse files Browse the repository at this point in the history
  • Loading branch information
Choraden authored and mmatczuk committed Oct 12, 2023
1 parent 8b2c96f commit 180744c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 17 deletions.
28 changes: 14 additions & 14 deletions runctx/runctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ type Group struct {

func NewGroup(fn ...func(ctx context.Context) error) *Group {
return &Group{
funcs: fn,
NotifySignals: DefaultNotifySignals,
funcs: fn,
}
}

Expand All @@ -50,20 +51,19 @@ func (g *Group) Run() error {
// It returns the first error returned by any of the functions.
// If the context is canceled, it returns nil.
func (g *Group) RunContext(ctx context.Context) error {
sigs := g.NotifySignals
if len(sigs) == 0 {
sigs = DefaultNotifySignals
}
ctx, unregisterSignals := signal.NotifyContext(ctx, sigs...)

var eg *errgroup.Group
eg, ctx = errgroup.WithContext(ctx)

eg.Go(func() error {
<-ctx.Done()
unregisterSignals()
return nil
})
if len(g.NotifySignals) > 0 {
var unregisterSignals context.CancelFunc
ctx, unregisterSignals = signal.NotifyContext(ctx, g.NotifySignals...)
eg, ctx = errgroup.WithContext(ctx)
eg.Go(func() error {
<-ctx.Done()
unregisterSignals()
return nil
})
} else {
eg, ctx = errgroup.WithContext(ctx)
}

for _, fn := range g.funcs {
fn := fn
Expand Down
6 changes: 3 additions & 3 deletions runctx/runctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestContextCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

var g Group
g := NewGroup()
g.Add(func(ctx context.Context) error {
<-ctx.Done()
return ctx.Err()
Expand All @@ -34,7 +34,7 @@ func TestContextCancel(t *testing.T) {
}

func TestSignal(t *testing.T) {
var g Group
g := NewGroup()
g.Add(func(ctx context.Context) error {
<-ctx.Done()
return ctx.Err()
Expand All @@ -51,7 +51,7 @@ func TestSignal(t *testing.T) {
func TestError(t *testing.T) {
testErr := errors.New("test")

var g Group
g := NewGroup()
g.Add(func(ctx context.Context) error {
<-ctx.Done()
return ctx.Err()
Expand Down

0 comments on commit 180744c

Please sign in to comment.