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