Skip to content

Commit 274d6c4

Browse files
committed
Use Atomic Bool variable instead of using mutex lock and unlock
Signed-off-by: kennyaz <115052215+kennyaz@users.noreply.github.com>
1 parent 6822e7c commit 274d6c4

File tree

1 file changed

+3
-7
lines changed

1 file changed

+3
-7
lines changed

pkg/fswatcher/fswatcher.go

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"path"
2323
"path/filepath"
2424
"sync"
25+
"sync/atomic"
2526

2627
"github.com/fsnotify/fsnotify"
2728
"go.uber.org/zap"
@@ -34,7 +35,7 @@ type FSWatcher struct {
3435
onChange func()
3536
mu sync.RWMutex
3637
stop chan struct{}
37-
isClosed bool
38+
isClosed atomic.Bool //default value is False
3839
wg sync.WaitGroup
3940
}
4041

@@ -71,7 +72,6 @@ func New(filepaths []string, onChange func(), logger *zap.Logger) (*FSWatcher, e
7172
fileHashContentMap: make(map[string]string),
7273
onChange: onChange,
7374
stop: make(chan struct{}),
74-
isClosed: false,
7575
}
7676

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

149149
// Close closes the watcher and stops the background go routine of FSWatcher.
150150
func (w *FSWatcher) Close() error {
151-
w.mu.Lock()
152-
defer w.mu.Unlock()
153-
154-
if !w.isClosed {
151+
if w.isClosed.CompareAndSwap(false, true) {
155152
close(w.stop)
156153
w.wg.Wait()
157-
w.isClosed = true
158154
}
159155

160156
return w.watcher.Close()

0 commit comments

Comments
 (0)