go-study/routine/options.go

60 lines
1.0 KiB
Go
Raw Normal View History

2023-12-26 16:07:46 +08:00
package routine
type options[T any] struct {
workers int
capacity int
taskFn func(T)
panicHandler func(any)
}
// Option function
type Option[T any] func(*options[T])
// setOptions 设置默认值
func setOptions[T any](opt ...Option[T]) options[T] {
opts := options[T]{
workers: 1,
capacity: 1,
}
for _, o := range opt {
o(&opts)
}
return opts
}
// WithWorkers 设置协程数
func WithWorkers[T any](workers int) Option[T] {
if workers <= 0 {
workers = 1
}
return func(o *options[T]) {
o.workers = workers
}
}
// WithCapacity 设置任务队列容量
func WithCapacity[T any](capacity int) Option[T] {
if capacity <= 0 {
capacity = 1
}
return func(o *options[T]) {
o.capacity = capacity
}
}
// WithTaskFn 设置任务函数
func WithTaskFn[T any](taskFn func(T)) Option[T] {
return func(o *options[T]) {
o.taskFn = taskFn
}
}
// WithPanicHandler 设置panic处理函数
func WithPanicHandler[T any](panicHandler func(any)) Option[T] {
return func(o *options[T]) {
o.panicHandler = panicHandler
}
}