Skip to content

Commit d077fb6

Browse files
committed
Fix data race in queue test
rand.Rand is not safe for concurrent use, and go test -race immediately detects the bug.
1 parent 7e1f576 commit d077fb6

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

queue/queue_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"math/rand"
55
"net/http"
66
"net/http/httptest"
7+
"sync"
78
"sync/atomic"
89
"testing"
910
"time"
@@ -16,6 +17,8 @@ func TestQueue(t *testing.T) {
1617
defer server.Close()
1718

1819
rng := rand.New(rand.NewSource(12387123712321232))
20+
var rngMu sync.Mutex
21+
1922
var (
2023
items uint32
2124
requests uint32
@@ -28,7 +31,9 @@ func TestQueue(t *testing.T) {
2831
panic(err)
2932
}
3033
put := func() {
34+
rngMu.Lock()
3135
t := time.Duration(rng.Intn(50)) * time.Microsecond
36+
rngMu.Unlock()
3237
url := server.URL + "/delay?t=" + t.String()
3338
atomic.AddUint32(&items, 1)
3439
q.AddURL(url)
@@ -49,7 +54,9 @@ func TestQueue(t *testing.T) {
4954
} else {
5055
atomic.AddUint32(&failure, 1)
5156
}
57+
rngMu.Lock()
5258
toss := rng.Intn(2) == 0
59+
rngMu.Unlock()
5360
if toss {
5461
put()
5562
}

0 commit comments

Comments
 (0)