85 lines
1.4 KiB
Go
85 lines
1.4 KiB
Go
package gtq
|
|
|
|
import (
|
|
"runtime"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
var testQ = NewQueue()
|
|
|
|
func testAdd(n int) {
|
|
for i := 0; i < n; i++ {
|
|
testQ.Add(func() {})
|
|
}
|
|
}
|
|
|
|
func testRemove(wg *sync.WaitGroup, removed chan int) {
|
|
defer wg.Done()
|
|
var i int
|
|
for testQ.Remove() != nil {
|
|
i++
|
|
}
|
|
removed <- i
|
|
}
|
|
|
|
func TestParallelQueueAdd(t *testing.T) {
|
|
max := runtime.GOMAXPROCS(0)
|
|
var wg sync.WaitGroup
|
|
for n := 0; n < max; n++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
testAdd(1000000)
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
t.Log("Queue size is", testQ.Length())
|
|
targetSize := max * 1000000
|
|
if testQ.Length() != targetSize {
|
|
t.Error("Queue size should be", targetSize)
|
|
}
|
|
}
|
|
|
|
func TestParallelQueueRemove(t *testing.T) {
|
|
target := testQ.Length()
|
|
var wg sync.WaitGroup
|
|
max := runtime.GOMAXPROCS(0)
|
|
removed := make(chan int, max)
|
|
for n := 0; n < max; n++ {
|
|
wg.Add(1)
|
|
go testRemove(&wg, removed)
|
|
}
|
|
wg.Wait()
|
|
close(removed)
|
|
var total int
|
|
for count := range removed {
|
|
total += count
|
|
}
|
|
if total != target {
|
|
t.Error("removed", total, "but expected", target)
|
|
}
|
|
t.Log("removed", total)
|
|
}
|
|
|
|
func BenchmarkParallelQueue(b *testing.B) {
|
|
testQ = NewQueue()
|
|
b.ResetTimer()
|
|
max := runtime.GOMAXPROCS(0)
|
|
var wg1, wg2 sync.WaitGroup
|
|
removed := make(chan int, max)
|
|
for i := 0; i < max; i++ {
|
|
wg1.Add(1)
|
|
wg2.Add(1)
|
|
go func() {
|
|
testAdd(b.N / (max * 2))
|
|
wg1.Done()
|
|
}()
|
|
go func() {
|
|
testRemove(&wg2, removed)
|
|
}()
|
|
}
|
|
wg1.Wait()
|
|
wg2.Wait()
|
|
}
|