@@ -34,31 +34,35 @@ type worker[T WorkItem] struct {
34
34
type NewTaskWorkerOptions func (* WorkerOptions )
35
35
36
36
type WorkerOptions struct {
37
- MaxParallelWorkItems int32
37
+ MaxParallelWorkItems * int32
38
38
}
39
39
40
40
func NewWorkerOptions () * WorkerOptions {
41
- return & WorkerOptions {
42
- MaxParallelWorkItems : 1 ,
43
- }
41
+ return & WorkerOptions {}
44
42
}
45
43
46
44
func WithMaxParallelism (n int32 ) NewTaskWorkerOptions {
47
45
return func (o * WorkerOptions ) {
48
- o .MaxParallelWorkItems = n
46
+ o .MaxParallelWorkItems = & n
49
47
}
50
48
}
51
49
52
50
func NewTaskWorker [T WorkItem ](p TaskProcessor [T ], logger Logger , opts ... NewTaskWorkerOptions ) TaskWorker [T ] {
53
- options := & WorkerOptions {MaxParallelWorkItems : 1 }
51
+ options := & WorkerOptions {}
54
52
for _ , configure := range opts {
55
53
configure (options )
56
54
}
55
+
56
+ var parallelLock chan struct {}
57
+ if options .MaxParallelWorkItems != nil {
58
+ parallelLock = make (chan struct {}, * options .MaxParallelWorkItems )
59
+ }
60
+
57
61
return & worker [T ]{
58
62
processor : p ,
59
63
logger : logger ,
60
64
workItems : make (chan T ),
61
- parallelLock : make ( chan struct {}, options . MaxParallelWorkItems ) ,
65
+ parallelLock : parallelLock ,
62
66
closeCh : make (chan struct {}),
63
67
}
64
68
}
@@ -87,15 +91,20 @@ func (w *worker[T]) Start(ctx context.Context) {
87
91
defer w .logger .Infof ("%v: worker stopped" , w .Name ())
88
92
89
93
for {
90
- select {
91
- case w .parallelLock <- struct {}{}:
92
- case <- ctx .Done ():
93
- return
94
+
95
+ if w .parallelLock != nil {
96
+ select {
97
+ case w .parallelLock <- struct {}{}:
98
+ case <- ctx .Done ():
99
+ return
100
+ }
94
101
}
95
102
96
103
wi , err := w .processor .NextWorkItem (ctx )
97
104
if err != nil {
98
- <- w .parallelLock
105
+ if w .parallelLock != nil {
106
+ <- w .parallelLock
107
+ }
99
108
100
109
if ctx .Err () != nil {
101
110
return
@@ -108,7 +117,9 @@ func (w *worker[T]) Start(ctx context.Context) {
108
117
w .wg .Add (1 )
109
118
go func () {
110
119
defer func () {
111
- <- w .parallelLock
120
+ if w .parallelLock != nil {
121
+ <- w .parallelLock
122
+ }
112
123
w .wg .Done ()
113
124
}()
114
125
w .processWorkItem (ctx , wi )
0 commit comments