Skip to content

Commit 4a33ea0

Browse files
imxybyonbiaoxiao
andauthored
chore: improve readability of lazyInit (gomodule#522)
Use sync.Once to make lazyInit more readable. Co-authored-by: yonbiaoxiao <yonbiaoxiao@tencent.com>
1 parent 51dc771 commit 4a33ea0

File tree

1 file changed

+3
-13
lines changed

1 file changed

+3
-13
lines changed

redis/pool.go

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323
"io"
2424
"strconv"
2525
"sync"
26-
"sync/atomic"
2726
"time"
2827
)
2928

@@ -161,11 +160,10 @@ type Pool struct {
161160
// the pool does not close connections based on age.
162161
MaxConnLifetime time.Duration
163162

164-
chInitialized uint32 // set to 1 when field ch is initialized
165-
166163
mu sync.Mutex // mu protects the following fields
167164
closed bool // set to true when the pool is closed.
168165
active int // the number of open connections in the pool
166+
initOnce sync.Once // the init ch once func
169167
ch chan struct{} // limits open connections when p.Wait is true
170168
idle idleList // idle connections
171169
waitCount int64 // total number of connections waited for.
@@ -339,13 +337,7 @@ func (p *Pool) Close() error {
339337
}
340338

341339
func (p *Pool) lazyInit() {
342-
// Fast path.
343-
if atomic.LoadUint32(&p.chInitialized) == 1 {
344-
return
345-
}
346-
// Slow path.
347-
p.mu.Lock()
348-
if p.chInitialized == 0 {
340+
p.initOnce.Do(func() {
349341
p.ch = make(chan struct{}, p.MaxActive)
350342
if p.closed {
351343
close(p.ch)
@@ -354,9 +346,7 @@ func (p *Pool) lazyInit() {
354346
p.ch <- struct{}{}
355347
}
356348
}
357-
atomic.StoreUint32(&p.chInitialized, 1)
358-
}
359-
p.mu.Unlock()
349+
})
360350
}
361351

362352
// waitVacantConn waits for a vacant connection in pool if waiting

0 commit comments

Comments
 (0)