Worker pool using goroutines
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
1.6 KiB

package pool
import (
"sync"
"sync/atomic"
"testing"
"time"
)
func TestPool(t *testing.T) {
var (
a uint64
wait sync.WaitGroup
)
pool := NewPool(4, 4)
if err := pool.Spawn(4); err != nil {
t.Fatal(err)
}
for i := 0; i < 16; i++ {
wait.Add(1)
pool.Schedule(func() {
atomic.AddUint64(&a, 1)
wait.Done()
})
}
for i := 0; i < 16; i++ {
wait.Add(1)
if err := pool.ScheduleUntil(func() {
atomic.AddUint64(&a, 1)
wait.Done()
}, time.Second); err != nil {
t.Fatal(err)
}
}
wait.Wait()
if a != 32 {
t.Fatal("expected a=32, got %d", a)
}
if err := pool.Close(); err != nil {
t.Fatal(err)
}
}
func TestPoolError(t *testing.T) {
var (
a uint64
)
pool := NewPool(1, 1)
if err := pool.Spawn(2); err != nil {
t.Logf("spawn error (expected): %v", err)
} else {
t.Fatal("expected pool.Spawn(2) to error")
}
// One job gets picked up by first worker slot, other is queued in work channel
for i := 0; i < 2; i++ {
pool.Schedule(func() {
time.Sleep(time.Second)
})
}
// Now all following scheduling should fail (unless your box is really slow...)
for i := 0; i < 2; i++ {
if err := pool.ScheduleUntil(func() {
time.Sleep(time.Second)
atomic.AddUint64(&a, 1)
}, time.Nanosecond); err == nil {
t.Logf("%d: expected timeout (is your box that fast!?)", i)
} else if err != nil {
t.Logf("schedule error (expected): %v", err)
}
}
if err := pool.Close(); err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
if err := pool.Schedule(func() {}); err == nil {
t.Fatal("expected error scheduling work on closed Pool")
} else {
t.Logf("schedule error (expected): %v", err)
}
}
}