-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactorygo.go
100 lines (85 loc) · 1.82 KB
/
factorygo.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
91
92
93
94
95
96
97
98
99
100
package factorygo
import (
"context"
"fmt"
"sync"
)
type Factory struct {
maxQueueSize int
maxWorkers int
workerJobsChan chan Job
cancelJobFuncs map[int]context.CancelFunc
mu sync.Mutex
}
func NewFactory(maxQueueSize, maxWorkers int) *Factory {
return &Factory{
maxQueueSize: maxQueueSize,
maxWorkers: maxWorkers,
workerJobsChan: make(chan Job, maxQueueSize),
cancelJobFuncs: make(map[int]context.CancelFunc),
}
}
func (f *Factory) Start() {
for i := 1; i <= f.maxWorkers; i++ {
go f.worker(i)
}
}
func (f *Factory) worker(workerID int) error {
for job := range f.workerJobsChan {
ctx, cancel := context.WithCancel(context.Background())
f.storeJob(job.ID, cancel)
err := job.Execute(ctx, workerID)
if err != nil {
return err
}
f.cleanupJob(job.ID)
}
return nil
}
func (f *Factory) AddJob(job Job) error {
select {
case f.workerJobsChan <- job:
return nil
default:
return fmt.Errorf("job queue is full")
}
}
type Job struct {
ID int
Executor func(ctx context.Context) error // Function to be executed
}
func (j *Job) Execute(ctx context.Context, workerID int) error {
// select {
// case <-ctx.Done():
// return nil
// default:
// fmt.Printf("--- end search job %d ---\n", j.ID)
// }
// Call the provided executor function
if j.Executor != nil {
return j.Executor(ctx)
}
return nil
}
func (f *Factory) storeJob(id int, cancel context.CancelFunc) {
f.mu.Lock()
f.cancelJobFuncs[id] = cancel
f.mu.Unlock()
}
func (f *Factory) cleanupJob(id int) {
f.mu.Lock()
delete(f.cancelJobFuncs, id)
f.mu.Unlock()
}
func (f *Factory) CancelJob(id int) error {
f.mu.Lock()
cancelFunc, ok := f.cancelJobFuncs[id]
if !ok {
f.mu.Unlock()
return fmt.Errorf("no cancel function found")
}
cancelFunc()
delete(f.cancelJobFuncs, id)
f.mu.Unlock()
return nil
}