Skip to content

Commit

Permalink
Wait until we're done connecting before returning from fillPool, to a…
Browse files Browse the repository at this point in the history
…void possible race between multiple goroutines opening new connections
  • Loading branch information
mdelah committed Feb 26, 2015
1 parent a979e19 commit 0033e98
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions connectionpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,8 @@ func (c *SimplePool) fillPool() {
c.hostMu.RLock()

//Walk through list of defined hosts
cHostConnected := make(chan int, len(c.hosts))
hostsPending := 0
for host := range c.hosts {
addr := JoinHostPort(host, c.cfg.Port)

Expand All @@ -251,14 +253,22 @@ func (c *SimplePool) fillPool() {

//This is reached if the host is responsive and needs more connections
//Create connections for host synchronously to mitigate flooding the host.
hostsPending++
go func(a string, conns int) {
defer func() { cHostConnected <- 1 }()
for ; conns < c.cfg.NumConns; conns++ {
c.connect(a)
}
}(addr, numConns)
}

c.hostMu.RUnlock()

//Wait until we're finished connecting to each host before returning
for hostsPending > 0 {
<- cHostConnected
hostsPending--
}
}

// Should only be called if c.mu is locked
Expand Down

0 comments on commit 0033e98

Please sign in to comment.