Skip to content

Commit

Permalink
fix: 🐛 Fix potential concurrency issue in EventQueue's (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
x1a2h1 authored Sep 2, 2024
1 parent e132d66 commit 924b4f7
Showing 1 changed file with 39 additions and 15 deletions.
54 changes: 39 additions & 15 deletions app/core/event/queue.go
Original file line number Diff line number Diff line change
@@ -1,55 +1,79 @@
package event

import (
"github.com/aimerny/kook-go/app/core/model"
"math"
"sync"

"github.com/aimerny/kook-go/app/core/model"
)

type EventQueue struct {
events map[int]*model.Signal
events *sync.Map
MinSn int
mu *sync.RWMutex
}

func NewEventQueue() *EventQueue {
return &EventQueue{
events: make(map[int]*model.Signal),
events: &sync.Map{},
MinSn: math.MaxInt,
mu: &sync.RWMutex{},
}
}

// Push returns min sn
func (eq *EventQueue) Push(signal *model.Signal) int {
eq.events[signal.SerialNumber] = signal
eq.mu.Lock()
defer eq.mu.Unlock()
eq.events.Store(signal.SerialNumber, signal)
if signal.SerialNumber < eq.MinSn {
eq.MinSn = signal.SerialNumber
}
return eq.MinSn
}

func (eq *EventQueue) Pop() *model.Signal {
if signal, ok := eq.events[eq.MinSn]; ok {
eq.events[eq.MinSn] = nil
delete(eq.events, eq.MinSn)
eq.resetMinKey()
return signal
eq.mu.Lock()
defer eq.mu.Unlock()
if signal, ok := eq.events.Load(eq.MinSn); ok {
if signal, ok := signal.(*model.Signal); ok {
eq.events.Delete(eq.MinSn)
eq.resetMinKey()
return signal
}
}
return nil
}

func (eq *EventQueue) IsEmpty() bool {
return len(eq.events) == 0
empty := true
eq.events.Range(func(key, value interface{}) bool {
empty = false
return false
})
return empty
}

func (eq *EventQueue) Clear() {
eq.events = make(map[int]*model.Signal)
eq.mu.Lock()
defer eq.mu.Unlock()
eq.events.Range(func(k, v interface{}) bool {
eq.events.Delete(k)
return true
})
eq.MinSn = math.MaxInt
}

func (eq *EventQueue) resetMinKey() {

eq.MinSn = math.MaxInt
for k := range eq.events {
if k < eq.MinSn {
eq.MinSn = k
eq.events.Range(func(k, v interface{}) bool {
if k, ok := k.(int); ok {
if k < eq.MinSn {
eq.MinSn = k
}
}
}
return true
})

}

0 comments on commit 924b4f7

Please sign in to comment.