fix: 并发安全地更新地图计数

This commit is contained in:
xinian
2026-04-02 22:38:02 +08:00
committed by cnb
parent 908f9bee98
commit f221b299cd
2 changed files with 20 additions and 10 deletions

View File

@@ -1,11 +1,14 @@
package space package space
import "sync"
// MapHotInfo 表示地图热度信息 // MapHotInfo 表示地图热度信息
type MapHotInfo struct { type MapHotInfo struct {
MapID uint32 `json:"mapId"` // 地图ID MapID uint32 `json:"mapId"` // 地图ID
Count int32 `struc:"uint32" json:"count"` // 地图里的人数 Count int32 `struc:"uint32" json:"count"` // 地图里的人数
} }
type MapTip struct { type MapTip struct {
mu sync.RWMutex
Count int `struc:"uint32" json:"count"` // 地图里的人数 Count int `struc:"uint32" json:"count"` // 地图里的人数
TipInfoS map[uint32]*TipInfo `json:"tipInfoS"` TipInfoS map[uint32]*TipInfo `json:"tipInfoS"`
} }
@@ -17,20 +20,27 @@ type TipInfo struct {
Diao []uint32 `json:"diao"` //掉落 Diao []uint32 `json:"diao"` //掉落
} }
func (m *MapTip) GetCount(t int) int { func (m *MapTip) ChangeCount(delta int) int {
m.mu.Lock()
defer m.mu.Unlock()
switch { if delta != 0 {
case t < 0: m.Count += delta
if m.Count > 0 { if m.Count < 0 {
m.Count -= t m.Count = 0
} }
case t > 0:
m.Count += t
} }
return m.Count return m.Count
} }
func (m *MapTip) CountValue() int {
m.mu.RLock()
defer m.mu.RUnlock()
return m.Count
}
var maphot = make(map[uint32]*MapTip, 0) var maphot = make(map[uint32]*MapTip, 0)
func GetMapHot() []MapHotInfo { func GetMapHot() []MapHotInfo {
@@ -38,7 +48,7 @@ func GetMapHot() []MapHotInfo {
for k, v := range maphot { for k, v := range maphot {
ret = append(ret, MapHotInfo{ ret = append(ret, MapHotInfo{
MapID: k, MapID: k,
Count: int32(v.GetCount(0)), Count: int32(v.CountValue()),
}) })
} }

View File

@@ -41,7 +41,7 @@ func (s *Space) LeaveMap(c common.PlayerI) {
current, ok := maphot[s.Super] current, ok := maphot[s.Super]
if ok { if ok {
current.GetCount(-1) current.ChangeCount(-1)
} }
if atomic.CompareAndSwapUint32(&s.Owner.UserID, c.GetInfo().UserID, 0) { if atomic.CompareAndSwapUint32(&s.Owner.UserID, c.GetInfo().UserID, 0) {
@@ -67,7 +67,7 @@ func (s *Space) EnterMap(c common.PlayerI) {
s.UserInfo.Store(c.GetInfo().UserID, *out) s.UserInfo.Store(c.GetInfo().UserID, *out)
curmaps, ok := maphot[s.Super] curmaps, ok := maphot[s.Super]
if ok { if ok {
curmaps.GetCount(1) curmaps.ChangeCount(1)
//atomic.AddInt32(maphot[s.Super], 1) //atomic.AddInt32(maphot[s.Super], 1)
} }