-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathworker.go
52 lines (41 loc) · 807 Bytes
/
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
package koi
import (
"context"
"log"
"golang.org/x/sync/semaphore"
)
type Worker struct {
QueueSize int
ConcurrentCount int64
Work func(any) any
}
type innerWorker struct {
Worker
ResultChan chan any
RequestChan chan any
Semaphore *semaphore.Weighted
}
func (i *innerWorker) work(request any) {
defer i.Release()
if result := i.Work(request); result != nil {
i.ResultChan <- result
}
}
func (i *innerWorker) Acquire() {
err := i.Semaphore.Acquire(context.Background(), 1)
if err != nil {
log.Println("failed to acquire lock")
}
}
func (i *innerWorker) Release() {
i.Semaphore.Release(1)
}
func (w Worker) Validate() error {
if w.ConcurrentCount < 1 {
return errMinConcurrentCount
}
if w.QueueSize < 0 {
return errNegativeQueueSize
}
return nil
}