From 21995ea4cdd352e599bbcf0f9bd276b683cb11cd Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Fri, 1 Apr 2022 20:44:32 +0400 Subject: [PATCH] Added mutex for lastPlayedCache. --- internal/radio/icecast.go | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/internal/radio/icecast.go b/internal/radio/icecast.go index db3bd42..7fe8c2c 100644 --- a/internal/radio/icecast.go +++ b/internal/radio/icecast.go @@ -7,6 +7,7 @@ import ( "net/http" "os/exec" "strings" + "sync" "time" "github.com/pkg/errors" @@ -65,19 +66,27 @@ func IcecastGetStatus(icecastURL string) (*IcecastStatus, error) { } func IcecastLastPlayedSongs(lastNSongs int, playlistPath string) ([]Song, error) { - if lpcLen := len(lastPlayedCache); lpcLen > 0 { - if lastNSongs > lpcLen { - lastNSongs = lpcLen + { + lastPlayedCacheMutex.Lock() + defer lastPlayedCacheMutex.Unlock() + if lpcLen := len(lastPlayedCache); lpcLen > 0 { + if lastNSongs > lpcLen { + lastNSongs = lpcLen + } + return lastPlayedCache[lpcLen-lastNSongs:], nil } - return lastPlayedCache[lpcLen-lastNSongs:], nil } return lastPlayedSongs(lastNSongs, playlistPath) } func IcecastLastSong(playlistPath string) (Song, error) { - if lpcLen := len(lastPlayedCache); lpcLen > 0 { - return lastPlayedCache[lpcLen-1], nil + { + lastPlayedCacheMutex.Lock() + defer lastPlayedCacheMutex.Unlock() + if lpcLen := len(lastPlayedCache); lpcLen > 0 { + return lastPlayedCache[lpcLen-1], nil + } } songs, err := lastPlayedSongs(1, playlistPath) @@ -121,6 +130,7 @@ func lastPlayedSongs(lastNSongs int, playlistPath string) ([]Song, error) { var playlistWatcher watcher.InotifyWatcher var playlistFired chan uint32 var lastPlayedCache []Song +var lastPlayedCacheMutex sync.Mutex func IcecastWatchPlaylist(playlistPath string, lastNSongs int) error { playlistWatcher, err := watcher.NewInotifyWatcher() @@ -141,6 +151,8 @@ func IcecastWatchPlaylist(playlistPath string, lastNSongs int) error { for { select { case <-playlistFired: + lastPlayedCacheMutex.Lock() + defer lastPlayedCacheMutex.Unlock() songs, err := lastPlayedSongs(lastNSongs, playlistPath) if err == nil && len(songs) > 0 { lastPlayedCache = songs