Skip to content

Commit

Permalink
Merge pull request #95 from libp2p/fix/avoid-useless-goroutines
Browse files Browse the repository at this point in the history
avoid spawning goroutines for canceled dials
  • Loading branch information
Stebalien authored Jan 23, 2019
2 parents c94e1b9 + 7061100 commit 10ab830
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions p2p/net/swarm/limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,26 @@ func newDialLimiterWithParams(df dialfunc, fdLimit, perPeerLimit int) *dialLimit
func (dl *dialLimiter) freeFDToken() {
dl.fdConsuming--

if len(dl.waitingOnFd) > 0 {
for len(dl.waitingOnFd) > 0 {
next := dl.waitingOnFd[0]
dl.waitingOnFd[0] = nil // clear out memory
dl.waitingOnFd = dl.waitingOnFd[1:]

if len(dl.waitingOnFd) == 0 {
dl.waitingOnFd = nil // clear out memory
// clear out memory.
dl.waitingOnFd = nil
}

// Skip over canceled dials instead of queuing up a goroutine.
if next.cancelled() {
dl.freePeerToken(next)
continue
}
dl.fdConsuming++

// we already have activePerPeer token at this point so we can just dial
go dl.executeDial(next)
return
}
}

Expand All @@ -99,18 +108,25 @@ func (dl *dialLimiter) freePeerToken(dj *dialJob) {
}

waitlist := dl.waitingOnPeerLimit[dj.peer]
if len(waitlist) > 0 {
for len(waitlist) > 0 {
next := waitlist[0]
if len(waitlist) == 1 {
waitlist[0] = nil // clear out memory
waitlist = waitlist[1:]

if len(waitlist) == 0 {
delete(dl.waitingOnPeerLimit, next.peer)
} else {
waitlist[0] = nil // clear out memory
dl.waitingOnPeerLimit[next.peer] = waitlist[1:]
dl.waitingOnPeerLimit[next.peer] = waitlist
}

if next.cancelled() {
continue
}

dl.activePerPeer[next.peer]++ // just kidding, we still want this token

dl.addCheckFdLimit(next)
return
}
}

Expand Down

0 comments on commit 10ab830

Please sign in to comment.