From 6cd6cd828fa443597c911d542766c6b5a665bf49 Mon Sep 17 00:00:00 2001 From: waterandair Date: Sun, 28 Jul 2019 14:56:57 +0800 Subject: [PATCH] protect pollSize and idleConnsLen with mutex (#1105) Fix poolSize and idleConnsLen when conn can't be created --- internal/pool/pool.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/internal/pool/pool.go b/internal/pool/pool.go index 1bcb74c..af62443 100644 --- a/internal/pool/pool.go +++ b/internal/pool/pool.go @@ -92,9 +92,7 @@ func NewConnPool(opt *Options) *ConnPool { idleConns: make([]*Conn, 0, opt.PoolSize), } - for i := 0; i < opt.MinIdleConns; i++ { - p.checkMinIdleConns() - } + p.checkMinIdleConns() if opt.IdleTimeout > 0 && opt.IdleCheckFrequency > 0 { go p.reaper(opt.IdleCheckFrequency) @@ -107,7 +105,7 @@ func (p *ConnPool) checkMinIdleConns() { if p.opt.MinIdleConns == 0 { return } - if p.poolSize < p.opt.PoolSize && p.idleConnsLen < p.opt.MinIdleConns { + for p.poolSize < p.opt.PoolSize && p.idleConnsLen < p.opt.MinIdleConns { p.poolSize++ p.idleConnsLen++ go p.addIdleConn() @@ -117,6 +115,10 @@ func (p *ConnPool) checkMinIdleConns() { func (p *ConnPool) addIdleConn() { cn, err := p.newConn(context.TODO(), true) if err != nil { + p.connsMu.Lock() + p.poolSize-- + p.idleConnsLen-- + p.connsMu.Unlock() return }