fix: logout discover dead lock (#1090)

This commit is contained in:
frank 2024-04-16 21:02:52 +08:00 committed by GitHub
parent 46b4efec56
commit 67bbbaf60d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 10 additions and 9 deletions

2
.gitignore vendored
View File

@ -186,3 +186,5 @@ iOSInjectionProject/
**/xcshareddata/WorkspaceSettings.xcsettings
# End of https://www.toptal.com/developers/gitignore/api/swift,xcode,Cobjective-c,osx
.idea

View File

@ -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
}

View File

@ -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.
@ -12,7 +13,7 @@ type CommonService struct {
cancel context.CancelFunc
ctx context.Context
wg sync.WaitGroup
started bool
started atomic.Bool
}
func NewCommonService() *CommonService {
@ -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
}
@ -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