-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathoptions.go
90 lines (75 loc) · 2.29 KB
/
options.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package goroutines
import (
"errors"
"time"
)
const (
// pool
defaultPreAllocWorkers = -1
defaultAdjustPeriod = 0
// batch
defaultBatchSize = 10
)
// PoolOption is an alias for functional argument.
type PoolOption func(opts *poolOption)
// poolOption contains all options which will be applied when initializing a pool.
type poolOption struct {
// taskQueueLength indicates the length of task queue.
// 0 (default value) means pure pubsub model without buffers.
taskQueueLength int
// preAllocWorkers indicates the number of workers to spawn when initializing Pool.
preAllocWorkers int
// workerAdjustPeriod indicates the duration to adjust the worker size.
// 0 (default value) means no need to adjust worker size.
workerAdjustPeriod time.Duration
}
func loadPoolOption(options ...PoolOption) *poolOption {
opts := &poolOption{
preAllocWorkers: defaultPreAllocWorkers,
workerAdjustPeriod: defaultAdjustPeriod,
}
for _, option := range options {
option(opts)
}
return opts
}
// WithTaskQueueLength sets up the length of task queue.
func WithTaskQueueLength(length int) PoolOption {
if length < 0 {
panic(errors.New("the length of task queue must be greater than or equal to zero"))
}
return func(opts *poolOption) {
opts.taskQueueLength = length
}
}
// WithPreAllocWorkers sets up the number of workers to spawn when initializing Pool.
func WithPreAllocWorkers(size int) PoolOption {
if size < 0 {
panic(errors.New("the pre-allocated number of workers must be greater than or equal to zero"))
}
return func(opts *poolOption) {
opts.preAllocWorkers = size
}
}
// WithWorkerAdjustPeriod sets up the duration to adjust the worker size.
func WithWorkerAdjustPeriod(period time.Duration) PoolOption {
if period <= 0 {
panic(errors.New("the period of adjusting workers must be greater than zero"))
}
return func(opts *poolOption) {
opts.workerAdjustPeriod = period
}
}
// BatchOption is an alias for functional argument in Batch
type BatchOption func(*batchOption)
type batchOption struct {
batchSize int
}
// WithBatchSize specifies the batch size used to forward tasks. If it is bigger
// enough, no more need to fork another goroutine to trigger Queue()
// defaultBatchSize is 10.
func WithBatchSize(size int) BatchOption {
return func(o *batchOption) {
o.batchSize = size
}
}