Skip to content

Commit c1855f4

Browse files
committed
Change how TestWaitingQueueSizeRace works
1 parent 3858984 commit c1855f4

File tree

1 file changed

+37
-25
lines changed

1 file changed

+37
-25
lines changed

workerpool_test.go

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -351,36 +351,48 @@ func TestStopRace(t *testing.T) {
351351
close(releaseChan)
352352
}
353353

354+
// Run this test with race detector to test that using WaitingQueueSize has no
355+
// race condition
354356
func TestWaitingQueueSizeRace(t *testing.T) {
355-
const maxQueueSize = 1
356-
wp := New(1)
357-
workRelChan := make(chan struct{})
358-
errChan := make(chan bool, 3)
359-
360-
go func() {
361-
for i := 0; i < 3; i++ {
362-
// Submit a new task only if # waiting in the queue is at maxQueueSize or more
363-
if wp.WaitingQueueSize() > maxQueueSize-1 {
364-
errChan <- true
365-
continue
366-
}
367-
wp.Submit(func() { <-workRelChan })
368-
// Wait for task to be removed from task queue.
369-
for len(wp.taskQueue) != 0 {
370-
time.Sleep(time.Microsecond)
357+
const (
358+
goroutines = 10
359+
tasks = 20
360+
workers = 5
361+
)
362+
wp := New(workers)
363+
maxChan := make(chan int)
364+
for g := 0; g < goroutines; g++ {
365+
go func() {
366+
max := 0
367+
// Submit 100 tasks, checking waiting queue size each time. Report
368+
// the maximum queue size seen.
369+
for i := 0; i < tasks; i++ {
370+
wp.Submit(func() {
371+
time.Sleep(time.Microsecond)
372+
})
373+
waiting := wp.WaitingQueueSize()
374+
if waiting > max {
375+
max = waiting
376+
}
371377
}
372-
}
373-
close(errChan)
374-
}()
378+
maxChan <- max
379+
}()
380+
}
375381

376-
ct := 0
377-
for range errChan {
378-
ct++
382+
// Find maximum queuesize seen by any thread.
383+
maxMax := 0
384+
for g := 0; g < goroutines; g++ {
385+
max := <-maxChan
386+
if max > maxMax {
387+
maxMax = max
388+
}
379389
}
380-
if ct != 1 {
381-
t.Fatal("Expected 1 task to be rejected due to # of tasks in queue", ct)
390+
if maxMax == 0 {
391+
t.Error("expected to see waiting queue size > 0")
392+
}
393+
if maxMax >= goroutines*tasks {
394+
t.Error("should not have seen all tasks on waiting queue")
382395
}
383-
close(workRelChan)
384396
}
385397

386398
func anyReady(w *WorkerPool) bool {

0 commit comments

Comments
 (0)