Skip to content

Commit d729c97

Browse files
committed
bugfix: race condition at GetNextConnection()
The `r.current` value can be changed by concurrent threads because the change happens under read-lock. We could use the atomic counter for a current connection number to avoid the race condition. Closes #309
1 parent 337ca73 commit d729c97

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Versioning](http://semver.org/spec/v2.0.0.html) except to the first release.
4242
### Fixed
4343

4444
- Flaky decimal/TestSelect (#300)
45+
- Race condition at roundRobinStrategy.GetNextConnection() (#309)
4546

4647
## [1.12.0] - 2023-06-07
4748

pool/round_robin.go

+7-7
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package pool
22

33
import (
44
"sync"
5+
"sync/atomic"
56

67
"github.com/tarantool/go-tarantool/v2"
78
)
@@ -10,8 +11,8 @@ type roundRobinStrategy struct {
1011
conns []*tarantool.Connection
1112
indexByAddr map[string]uint
1213
mutex sync.RWMutex
13-
size uint
14-
current uint
14+
size uint64
15+
current uint64
1516
}
1617

1718
func newRoundRobinStrategy(size int) *roundRobinStrategy {
@@ -98,13 +99,12 @@ func (r *roundRobinStrategy) AddConn(addr string, conn *tarantool.Connection) {
9899
r.conns[idx] = conn
99100
} else {
100101
r.conns = append(r.conns, conn)
101-
r.indexByAddr[addr] = r.size
102+
r.indexByAddr[addr] = uint(r.size)
102103
r.size += 1
103104
}
104105
}
105106

106-
func (r *roundRobinStrategy) nextIndex() uint {
107-
ret := r.current % r.size
108-
r.current++
109-
return ret
107+
func (r *roundRobinStrategy) nextIndex() uint64 {
108+
next := atomic.AddUint64(&r.current, 1)
109+
return (next - 1) % r.size
110110
}

0 commit comments

Comments
 (0)