go-study/routine/pool_test.go

46 lines
701 B
Go
Raw Normal View History

2023-12-23 14:33:52 +08:00
package routine
import (
2023-12-26 16:07:46 +08:00
"fmt"
2023-12-23 14:33:52 +08:00
"runtime"
2023-12-26 16:07:46 +08:00
"runtime/debug"
2023-12-23 14:33:52 +08:00
"sync/atomic"
"testing"
"github.com/brildum/testify/assert"
)
func TestPool(t *testing.T) {
num := runtime.NumCPU()
var sum atomic.Int32
2023-12-26 16:07:46 +08:00
2023-12-28 14:58:06 +08:00
task := func(t T) {
num := t.(int32)
2023-12-23 14:33:52 +08:00
if num < 0 {
panic("unable to handle negative numbers")
}
sum.Add(num)
2023-12-26 16:07:46 +08:00
}
handler := func(r any) {
fmt.Printf("Panic: %v\n %s", r, string(debug.Stack()))
}
pool := NewPool(
2023-12-28 14:58:06 +08:00
WithWorkers(num),
WithCapacity(num),
2023-12-26 16:07:46 +08:00
WithTaskFn(task),
2023-12-28 14:58:06 +08:00
WithPanicHandler(handler),
2023-12-26 16:07:46 +08:00
)
2023-12-23 14:33:52 +08:00
pool.Start()
for i := int32(1000); i >= -1; i-- {
pool.Push(i)
}
pool.Wait()
if assert.Equal(t, int32(500500), sum.Load()) {
t.Log("the sum value is right")
}
}