simple.simpleProtocolMgr实现的相关问题
RT,在view代码的过程中发现一些问题:
- 声明的sync.Mutex锁没有使用
- 所有更改或写操作没有加锁
- supportedN和unsupportedN使用开启协程的方式调用不合理,可能会导致乱序执行问题
func (s *simpleProtocolMgr) callNotifyIfChanged(pid peer.ID, news []protocol.ID) {
if len(news) == 0 {
return
}
// check new
if s.supportedN != nil {
for i := range news {
if !s.protocolBook.ContainsProtocol(pid, news[i]) {
go s.supportedN(news[i], pid) // 这里应该删除go
}
}
}
// check drop
if s.unsupportedN != nil {
tempMap := make(map[protocol.ID]struct{})
for i := range news {
tempMap[news[i]] = struct{}{}
}
oldSupported := s.protocolBook.GetProtocols(pid)
for idx := range oldSupported {
_, notDrop := tempMap[oldSupported[idx]]
if !notDrop {
go s.unsupportedN(oldSupported[idx], pid) // 这里应该删除go
}
}
}
}
改进建议:
ProtocolManager应该是只有在节点连接/断开、新协议注册、旧协议注销时被调用,使用频率并不会特别高,建议使用sync.RWMutex代替sync.Mutex,使用map代替sync.Map