From d6792545168f19d938d7553369f148d24b22f996 Mon Sep 17 00:00:00 2001 From: Simone Gotti Date: Mon, 11 Nov 2019 14:47:22 +0100 Subject: [PATCH] readdb: improve HandleEvents goroutine exiting Rename errCh to doneCh (error is not needed) and always send to it when one of the HandleEvents functions exits (not only on error). This will ensure that all the goroutines will be stopped also if one of them returns without an error. --- internal/services/configstore/readdb/readdb.go | 7 ++++--- internal/services/runservice/readdb/readdb.go | 12 ++++++------ 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/internal/services/configstore/readdb/readdb.go b/internal/services/configstore/readdb/readdb.go index ff8f579..78c6e57 100644 --- a/internal/services/configstore/readdb/readdb.go +++ b/internal/services/configstore/readdb/readdb.go @@ -445,18 +445,19 @@ func (r *ReadDB) Run(ctx context.Context) error { } } - errCh := make(chan error, 1) + doneCh := make(chan struct{}, 2) hctx, cancel := context.WithCancel(ctx) wg := &sync.WaitGroup{} wg.Add(1) + go func() { r.log.Infof("starting handleEvents") if err := r.handleEvents(hctx); err != nil { r.log.Errorf("handleEvents err: %+v", err) - errCh <- err } wg.Done() + doneCh <- struct{}{} }() select { @@ -464,7 +465,7 @@ func (r *ReadDB) Run(ctx context.Context) error { r.log.Infof("readdb exiting") cancel() return nil - case <-errCh: + case <-doneCh: // cancel context and wait for the all the goroutines to exit cancel() wg.Wait() diff --git a/internal/services/runservice/readdb/readdb.go b/internal/services/runservice/readdb/readdb.go index 52ab5c0..746c251 100644 --- a/internal/services/runservice/readdb/readdb.go +++ b/internal/services/runservice/readdb/readdb.go @@ -306,28 +306,28 @@ func (r *ReadDB) Run(ctx context.Context) error { } } - errCh := make(chan error, 2) + doneCh := make(chan struct{}, 2) hctx, cancel := context.WithCancel(ctx) wg := &sync.WaitGroup{} - wg.Add(1) + wg.Add(2) + go func() { r.log.Infof("starting handleEvents") if err := r.handleEvents(hctx); err != nil { r.log.Errorf("handleEvents err: %+v", err) - errCh <- err } wg.Done() + doneCh <- struct{}{} }() - wg.Add(1) go func() { r.log.Infof("starting handleEventsOST") if err := r.handleEventsOST(hctx); err != nil { r.log.Errorf("handleEventsOST err: %+v", err) - errCh <- err } wg.Done() + doneCh <- struct{}{} }() select { @@ -335,7 +335,7 @@ func (r *ReadDB) Run(ctx context.Context) error { r.log.Infof("readdb exiting") cancel() return nil - case <-errCh: + case <-doneCh: // cancel context and wait for the all the goroutines to exit cancel() wg.Wait()