-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.go
More file actions
63 lines (54 loc) · 1.06 KB
/
Copy pathworker.go
File metadata and controls
63 lines (54 loc) · 1.06 KB
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
package ungo
import "slices"
var workers Lazy[*SmallMap[int, *Worker]] = Lazy[*SmallMap[int, *Worker]]{
initializer: func() *SmallMap[int, *Worker] {
return NewSmallMap[int, *Worker](0xFFFF)
},
}
type Worker struct {
id int
result Result[any]
isRunning bool
isCancelled bool
fn func() Result[any]
}
func (w *Worker) GetResult() Result[any] {
return w.result
}
func (w *Worker) SetResult(result Result[any]) {
w.result = result
}
func GetWorker(id int) Optional[*Worker] {
worker, ok := workers.Value().Get(id)
if !ok {
return EmptyOptional[*Worker]()
}
return MakeOptional(worker)
}
func MakeWorker(fn func() Result[any]) *Worker {
var id int
IDs := workers.Value().Keys()
for slices.Contains(IDs, id) {
id++
}
worker := &Worker{
id: id,
fn: fn,
}
workers.Value().Set(worker.id, worker)
return worker
}
func (w *Worker) Run() {
if w.isRunning {
return
}
w.isRunning = true
go func() {
w.result = w.fn()
workers.Value().Delete(w.id)
w.isRunning = false
}()
}
func (w *Worker) Cancel() {
w.isCancelled = true
}