From 2250cb752bea24ff63619b3c1530eb96794f3d5a Mon Sep 17 00:00:00 2001 From: yyforyongyu Date: Tue, 14 Dec 2021 03:02:41 +0800 Subject: [PATCH] discovery: shorten mutex locking closure --- discovery/gossiper.go | 9 +++++++-- discovery/reliable_sender.go | 11 ++++++++--- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/discovery/gossiper.go b/discovery/gossiper.go index e96c1bfb9..690b5a564 100644 --- a/discovery/gossiper.go +++ b/discovery/gossiper.go @@ -1822,8 +1822,10 @@ func (d *AuthenticatedGossiper) processNetworkAnnouncement( // making decisions based on this DB state, before it // writes to the DB. d.channelMtx.Lock(msg.ShortChannelID.ToUint64()) - defer d.channelMtx.Unlock(msg.ShortChannelID.ToUint64()) - if err := d.cfg.Router.AddEdge(edge, schedulerOp...); err != nil { + err := d.cfg.Router.AddEdge(edge, schedulerOp...) + if err != nil { + defer d.channelMtx.Unlock(msg.ShortChannelID.ToUint64()) + // If the edge was rejected due to already being known, // then it may be that case that this new message has a // fresh channel proof, so we'll check. @@ -1871,6 +1873,9 @@ func (d *AuthenticatedGossiper) processNetworkAnnouncement( return nil, false } + // If err is nil, release the lock immediately. + d.channelMtx.Unlock(msg.ShortChannelID.ToUint64()) + // If we earlier received any ChannelUpdates for this channel, // we can now process them, as the channel is added to the // graph. diff --git a/discovery/reliable_sender.go b/discovery/reliable_sender.go index 882eeebee..b22a15ae1 100644 --- a/discovery/reliable_sender.go +++ b/discovery/reliable_sender.go @@ -131,10 +131,10 @@ spawnHandler: // spawnPeerMsgHandler spawns a peerHandler for the given peer if there isn't // one already active. The boolean returned signals whether there was already // one active or not. -func (s *reliableSender) spawnPeerHandler(peerPubKey [33]byte) (peerManager, bool) { - s.activePeersMtx.Lock() - defer s.activePeersMtx.Unlock() +func (s *reliableSender) spawnPeerHandler( + peerPubKey [33]byte) (peerManager, bool) { + s.activePeersMtx.Lock() msgHandler, ok := s.activePeers[peerPubKey] if !ok { msgHandler = peerManager{ @@ -142,7 +142,12 @@ func (s *reliableSender) spawnPeerHandler(peerPubKey [33]byte) (peerManager, boo done: make(chan struct{}), } s.activePeers[peerPubKey] = msgHandler + } + s.activePeersMtx.Unlock() + // If this is a newly initiated peerManager, we will create a + // peerHandler. + if !ok { s.wg.Add(1) go s.peerHandler(msgHandler, peerPubKey) }