-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
55 lines (43 loc) · 1.04 KB
/
worker.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
package koi
import (
"reflect"
)
type NoReturn int
const None NoReturn = 0
type Worker[T any, E any] struct {
QueueSize uint
ConcurrentCount int
Work func(T) E
ResultChan chan E
RequestChan chan T
}
func NewWoker[T any, E any](work func(T) E, queueSize uint, concurrentCount int) (*Worker[T, E], error) {
w := &Worker[T, E]{
QueueSize: queueSize,
ConcurrentCount: concurrentCount,
Work: work,
ResultChan: make(chan E, queueSize),
RequestChan: make(chan T, queueSize),
}
return w, w.Validate()
}
func MustNewWoker[T any, E any](work func(T) E, queueSize uint, concurrentCount int) *Worker[T, E] {
w, err := NewWoker(work, queueSize, concurrentCount)
if err != nil {
panic(err)
}
return w
}
func (i *Worker[T, E]) work() {
for request := range i.RequestChan {
if res := i.Work(request); reflect.TypeOf(res) != reflect.TypeOf(None) {
i.ResultChan <- res
}
}
}
func (i Worker[T, E]) Validate() error {
if i.ConcurrentCount < 1 {
return ErrMinConcurrentCount
}
return nil
}