Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: data race in roundrobin balancer #1251

Merged
merged 1 commit into from
Dec 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions balancer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"math/rand"
"sort"
"sync"
"sync/atomic"
)

// The Balancer interface provides an abstraction of the message distribution
Expand Down Expand Up @@ -42,8 +41,10 @@ func (f BalancerFunc) Balance(msg Message, partitions ...int) int {
type RoundRobin struct {
ChunkSize int
// Use a 32 bits integer so RoundRobin values don't need to be aligned to
// apply atomic increments.
// apply increments.
counter uint32

mutex sync.Mutex
}

// Balance satisfies the Balancer interface.
Expand All @@ -52,14 +53,17 @@ func (rr *RoundRobin) Balance(msg Message, partitions ...int) int {
}

func (rr *RoundRobin) balance(partitions []int) int {
rr.mutex.Lock()
defer rr.mutex.Unlock()

if rr.ChunkSize < 1 {
rr.ChunkSize = 1
}

length := len(partitions)
counterNow := atomic.LoadUint32(&rr.counter)
counterNow := rr.counter
offset := int(counterNow / uint32(rr.ChunkSize))
atomic.AddUint32(&rr.counter, 1)
rr.counter++
return partitions[offset%length]
}

Expand Down