Skip to content

Commit

Permalink
Use Atomic Bool variable instead of using mutex lock and unlock
Browse files Browse the repository at this point in the history
  • Loading branch information
kennyaz committed Jun 8, 2023
1 parent 2f98a9e commit c9334ad
Showing 1 changed file with 3 additions and 7 deletions.
10 changes: 3 additions & 7 deletions pkg/fswatcher/fswatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"path"
"path/filepath"
"sync"
"sync/atomic"

"github.com/fsnotify/fsnotify"
"go.uber.org/zap"
Expand All @@ -34,7 +35,7 @@ type FSWatcher struct {
onChange func()
mu sync.RWMutex
stop chan struct{}
isClosed bool
isClosed atomic.Bool //default value is False
wg sync.WaitGroup
}

Expand Down Expand Up @@ -71,7 +72,6 @@ func New(filepaths []string, onChange func(), logger *zap.Logger) (*FSWatcher, e
fileHashContentMap: make(map[string]string),
onChange: onChange,
stop: make(chan struct{}),
isClosed: false,
}

if err = w.setupWatchedPaths(filepaths); err != nil {
Expand Down Expand Up @@ -148,13 +148,9 @@ func (w *FSWatcher) watch() {

// Close closes the watcher and stops the background go routine of FSWatcher.
func (w *FSWatcher) Close() error {
w.mu.Lock()
defer w.mu.Unlock()

if !w.isClosed {
if w.isClosed.CompareAndSwap(false, true) {
close(w.stop)
w.wg.Wait()
w.isClosed = true
}

return w.watcher.Close()
Expand Down

0 comments on commit c9334ad

Please sign in to comment.