Skip to content

Commit

Permalink
Fix data race in loadAlignmentPatternLoc (#104)
Browse files Browse the repository at this point in the history
* Fix data race in loadAlignmentPatternLoc

* Add test for loadAlignmentPatternLoc with concurrent access

* go test with -race flag
  • Loading branch information
mnrtks authored Apr 10, 2024
1 parent d965020 commit eab5cc3
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,21 @@ jobs:
stable: false

- name: Build
run: go build -v ./...
run: go build -v -race ./...

- name: Test qrcode
working-directory: .
run: go test -v ./...
run: go test -v -race ./...
continue-on-error: false

- name: Test writer/standard
working-directory: ./writer/standard
run: go mod tidy && mkdir testdata && go test -v ./...
run: go mod tidy && mkdir testdata && go test -v -race ./...
continue-on-error: false

- name: Test writer/terminal
working-directory: ./writer/terminal
run: go mod tidy && mkdir testdata && go test -v ./...
run: go mod tidy && mkdir testdata && go test -v -race ./...
continue-on-error: false

- name: Upload coverage reports to Codecov
Expand Down
8 changes: 7 additions & 1 deletion version.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"log"
"strconv"
"sync"

// "github.com/skip2/go-qrcode/bitset"
"github.com/yeqown/reedsolomon/binary"
Expand Down Expand Up @@ -353,7 +354,8 @@ var (
40: {6, 30, 58, 86, 114, 142, 170},
}

alignPatternCache = map[int][]loc{}
alignPatternCache = map[int][]loc{}
alignPatternCacheMu sync.Mutex
)

// loc point position(x,y)
Expand All @@ -367,6 +369,10 @@ func loadAlignmentPatternLoc(ver int) (locs []loc) {
if ver < 2 {
return
}

alignPatternCacheMu.Lock()
defer alignPatternCacheMu.Unlock()

var ok bool
if locs, ok = alignPatternCache[ver]; ok {
return
Expand Down
17 changes: 17 additions & 0 deletions version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"math/rand"
"reflect"
"strings"
"sync"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -231,6 +232,22 @@ func Test_binarySearchVersion_all(t *testing.T) {
}
}

func Test_loadAlignmentPatternLoc_concurrentAccess(t *testing.T) {
var wg sync.WaitGroup

for ver := 2; ver <= _VERSION_COUNT; ver++ {
wg.Add(1)

go func(v int) {
got := loadAlignmentPatternLoc(v)
assert.NotEmpty(t, got)
wg.Done()
}(ver)
}

wg.Wait()
}

// // go test -run=NONE -bench . -count 10 > new/old.txt
func Benchmark_loadVersion_top(b *testing.B) {
for i := 0; i < b.N; i++ {
Expand Down

0 comments on commit eab5cc3

Please sign in to comment.