Skip to content

Commit c887acd

Browse files
authored
Room.lastMsgのrace回避 (#96)
T/O
2 parents 6e5aee3 + 4d9031a commit c887acd

1 file changed

Lines changed: 14 additions & 3 deletions

File tree

‎server/game/room.go‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ type Room struct {
4242
masterOrder []ClientID
4343
watchers map[ClientID]*Client
4444

45-
lastMsg binary.Dict // map[clientID]unixtime_millisec
45+
muLastMsg sync.RWMutex
46+
lastMsg binary.Dict // map[clientID]unixtime_millisec
4647

4748
logger log.Logger
4849

@@ -166,18 +167,24 @@ func (r *Room) Done() <-chan struct{} {
166167

167168
func (r *Room) writeLastMsg(cid ClientID) {
168169
millisec := uint64(time.Now().UnixNano()) / 1000000
170+
r.muLastMsg.Lock()
171+
defer r.muLastMsg.Unlock()
169172
r.lastMsg[string(cid)] = binary.MarshalULong(millisec)
170173
}
171174

172175
func (r *Room) removeLastMsg(cid ClientID) {
176+
r.muLastMsg.Lock()
177+
defer r.muLastMsg.Unlock()
173178
delete(r.lastMsg, string(cid))
174179
}
175180

176181
// UpdateLastMsg : PlayerがMsgを受信したとき更新する.
177182
// 既に登録されているPlayerのみ書き込み (watcherを含めないため)
178183
func (r *Room) updateLastMsg(cid ClientID) {
179-
id := string(cid)
180-
if _, ok := r.lastMsg[id]; ok {
184+
r.muLastMsg.Lock()
185+
_, ok := r.lastMsg[string(cid)]
186+
r.muLastMsg.Unlock()
187+
if ok {
181188
r.writeLastMsg(cid)
182189
}
183190
}
@@ -515,7 +522,9 @@ func (r *Room) msgPing(msg *MsgPing) {
515522
}
516523
}
517524
msg.Sender.logger.Debugf("ping %v: %v", msg.Sender.Id, msg.Timestamp)
525+
r.muLastMsg.RLock()
518526
ev := binary.NewEvPong(msg.Timestamp, r.RoomInfo.Watchers, r.lastMsg)
527+
r.muLastMsg.RUnlock()
519528
msg.Sender.SendSystemEvent(ev)
520529
}
521530

@@ -783,13 +792,15 @@ func (r *Room) msgGetRoomInfo(msg *MsgGetRoomInfo) {
783792
cis = append(cis, r.players[id].ClientInfo.Clone())
784793
}
785794
lmt := make(map[string]uint64)
795+
r.muLastMsg.RLock()
786796
for p, d := range r.lastMsg {
787797
t, _, err := binary.UnmarshalAs(d, binary.TypeULong)
788798
if err != nil {
789799
r.logger.Errorf("Unmarshal LastMsg[%s]: %w", p, err)
790800
}
791801
lmt[p] = t.(uint64)
792802
}
803+
r.muLastMsg.RUnlock()
793804

794805
msg.Res <- &pb.GetRoomInfoRes{
795806
RoomInfo: ri,

0 commit comments

Comments
 (0)