Skip to content

Commit

Permalink
fix: logout discover dead lock (#1085)
Browse files Browse the repository at this point in the history
  • Loading branch information
qfrank authored Apr 15, 2024
1 parent dd81e1d commit 6d889ca
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
2 changes: 0 additions & 2 deletions waku/v2/service/common_discovery_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ func (sp *CommonDiscoveryService) GetListeningChan() <-chan PeerData {
return sp.channel
}
func (sp *CommonDiscoveryService) PushToChan(data PeerData) bool {
sp.RLock()
defer sp.RUnlock()
if err := sp.ErrOnNotRunning(); err != nil {
return false
}
Expand Down
15 changes: 8 additions & 7 deletions waku/v2/service/common_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"sync"
"sync/atomic"
)

// this is common layout for all the services that require mutex protection and a guarantee that all running goroutines will be finished before stop finishes execution. This guarantee comes from waitGroup all one has to use CommonService.WaitGroup() in the goroutines that should finish by the end of stop function.
Expand All @@ -12,7 +13,7 @@ type CommonService struct {
cancel context.CancelFunc
ctx context.Context
wg sync.WaitGroup
started bool
started atomic.Bool
}

func NewCommonService() *CommonService {
Expand All @@ -28,13 +29,13 @@ func NewCommonService() *CommonService {
func (sp *CommonService) Start(ctx context.Context, fn func() error) error {
sp.Lock()
defer sp.Unlock()
if sp.started {
if sp.started.Load() {
return ErrAlreadyStarted
}
sp.started = true
sp.started.Store(true)
sp.ctx, sp.cancel = context.WithCancel(ctx)
if err := fn(); err != nil {
sp.started = false
sp.started.Store(false)
sp.cancel()
return err
}
Expand All @@ -48,18 +49,18 @@ var ErrNotStarted = errors.New("not started")
func (sp *CommonService) Stop(fn func()) {
sp.Lock()
defer sp.Unlock()
if !sp.started {
if !sp.started.Load() {
return
}
sp.cancel()
fn()
sp.wg.Wait()
sp.started = false
sp.started.Store(false)
}

// This is not a mutex protected function, it is up to the caller to use it in a mutex protected context
func (sp *CommonService) ErrOnNotRunning() error {
if !sp.started {
if !sp.started.Load() {
return ErrNotStarted
}
return nil
Expand Down

0 comments on commit 6d889ca

Please sign in to comment.