From cbfc1549ede517bcfd088519340b654cc38037cd Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Sun, 1 Oct 2023 04:18:43 +0400 Subject: [PATCH] Added a mutex for Listeners struct for thread safety. --- internal/radio/listeners.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/internal/radio/listeners.go b/internal/radio/listeners.go index a7bfc3d..f213612 100644 --- a/internal/radio/listeners.go +++ b/internal/radio/listeners.go @@ -4,10 +4,12 @@ import ( "errors" "fmt" "math" + "sync" ) // Listeners stores the current and peak numbers of listeners. type Listeners struct { + mut sync.Mutex current, peak int } @@ -18,16 +20,22 @@ func NewListeners() *Listeners { // Current returns a number of current listeners. func (l *Listeners) Current() int { + l.mut.Lock() + defer l.mut.Unlock() return l.current } // Current returns a number of peak listeners. func (l *Listeners) Peak() int { + l.mut.Lock() + defer l.mut.Unlock() return l.peak } // Inc increments by 1 a current number of listeners and updates a peak number. func (l *Listeners) Inc() int { + l.mut.Lock() + defer l.mut.Unlock() if l.current == math.MaxInt { // We panic here because if this will ever happen, then something's going certainly wrong. panic(fmt.Sprint("a current number of listeners exceeded MaxInt which is", math.MaxInt)) @@ -42,6 +50,8 @@ func (l *Listeners) Inc() int { // Dec decrements by 1 a current number of listeners. An error will occur if // a resulting number is less than 0. func (l *Listeners) Dec() (int, error) { + l.mut.Lock() + defer l.mut.Unlock() if l.current == 0 { return l.current, errors.New("an attempt to decrement a number of current listeners down to less than 0") }