Skip to content

Commit 3e77a2f

Browse files
committed
pool: fix 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 44db92b commit 3e77a2f

File tree

3 files changed

+37
-7
lines changed

3 files changed

+37
-7
lines changed

CHANGELOG.md

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

4848
- Flaky decimal/TestSelect (#300)
49+
- Race condition at roundRobinStrategy.GetNextConnection() (#309)
4950

5051
## [1.12.0] - 2023-06-07
5152

pool/connection_pool_test.go

+29
Original file line numberDiff line numberDiff line change
@@ -2231,6 +2231,35 @@ func TestDo(t *testing.T) {
22312231
require.NotNilf(t, resp, "response is nil after Ping")
22322232
}
22332233

2234+
func TestDo_concurrent(t *testing.T) {
2235+
roles := []bool{true, true, false, true, false}
2236+
2237+
err := test_helpers.SetClusterRO(servers, connOpts, roles)
2238+
require.Nilf(t, err, "fail to set roles for cluster")
2239+
2240+
connPool, err := pool.Connect(servers, connOpts)
2241+
require.Nilf(t, err, "failed to connect")
2242+
require.NotNilf(t, connPool, "conn is nil after Connect")
2243+
2244+
defer connPool.Close()
2245+
2246+
req := tarantool.NewPingRequest()
2247+
const concurrency = 100
2248+
var wg sync.WaitGroup
2249+
wg.Add(concurrency)
2250+
2251+
for i := 0; i < concurrency; i++ {
2252+
go func() {
2253+
defer wg.Done()
2254+
2255+
_, err := connPool.Do(req, pool.ANY).Get()
2256+
assert.Nil(t, err)
2257+
}()
2258+
}
2259+
2260+
wg.Wait()
2261+
}
2262+
22342263
func TestNewPrepared(t *testing.T) {
22352264
test_helpers.SkipIfSQLUnsupported(t)
22362265

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)