Skip to content

Commit 1708f5b

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 1708f5b

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
@@ -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/connection_pool_test.go

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

2218+
func TestDo_concurrent(t *testing.T) {
2219+
roles := []bool{true, true, false, true, false}
2220+
2221+
err := test_helpers.SetClusterRO(servers, connOpts, roles)
2222+
require.Nilf(t, err, "fail to set roles for cluster")
2223+
2224+
connPool, err := pool.Connect(servers, connOpts)
2225+
require.Nilf(t, err, "failed to connect")
2226+
require.NotNilf(t, connPool, "conn is nil after Connect")
2227+
2228+
defer connPool.Close()
2229+
2230+
req := tarantool.NewPingRequest()
2231+
const concurrency = 100
2232+
var wg sync.WaitGroup
2233+
wg.Add(concurrency)
2234+
2235+
for i := 0; i < concurrency; i++ {
2236+
go func() {
2237+
defer wg.Done()
2238+
2239+
_, err := connPool.Do(req, pool.ANY).Get()
2240+
assert.Nil(t, err)
2241+
}()
2242+
}
2243+
2244+
wg.Wait()
2245+
}
2246+
22182247
func TestNewPrepared(t *testing.T) {
22192248
test_helpers.SkipIfSQLUnsupported(t)
22202249

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)