1
0

Added mutex for lastPlayedCache.

This commit is contained in:
Alexander Andreev 2022-04-01 20:44:32 +04:00
parent d3ffd01e0a
commit 21995ea4cd
Signed by: Arav
GPG Key ID: 1327FE8A374CC86F

View File

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