Skip to content

Commit

Permalink
Use sync.Once in file.Watcher.Stop
Browse files Browse the repository at this point in the history
Avoid potential race condition mutating the watcher's quit channel
while it is being read by the file check loop goroutine.
  • Loading branch information
wedaly committed Dec 23, 2023
1 parent d64594c commit 0a9af65
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions file/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io/fs"
"log"
"os"
"sync"
"time"
)

Expand All @@ -26,6 +27,7 @@ type Watcher struct {

changedChan chan struct{}
quitChan chan struct{}
stopOnce sync.Once
}

// NewWatcherForNewFile returns a watcher for a file that does not yet exist on disk.
Expand Down Expand Up @@ -69,12 +71,12 @@ func (w *Watcher) Path() string {

// Stop stops the watcher from checking for changes.
func (w *Watcher) Stop() {
if w.quitChan == nil {
return
}
log.Printf("Stopping file watcher for %s...\n", w.path)
close(w.quitChan)
w.quitChan = nil
w.stopOnce.Do(func() {
if w.quitChan != nil {
log.Printf("Stopping file watcher for %s...\n", w.path)
close(w.quitChan)
}
})
}

// CheckFileMovedOrDeleted checks whether the file used to exist
Expand Down

0 comments on commit 0a9af65

Please sign in to comment.