-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrency.go
More file actions
88 lines (76 loc) · 1.51 KB
/
concurrency.go
File metadata and controls
88 lines (76 loc) · 1.51 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
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
package structures
import (
"context"
"sync"
)
type ConcurrencyHandler struct {
curTaskIdx int
taskCh chan ConcurrencyTask
concurrencyCh chan struct{}
wg *sync.WaitGroup
}
func NewConcurrencyHandler(maxConcurrentTasks int) *ConcurrencyHandler {
wg := sync.WaitGroup{}
wg.Add(1)
return &ConcurrencyHandler{
curTaskIdx: 0,
taskCh: make(chan ConcurrencyTask),
concurrencyCh: make(chan struct{}, maxConcurrentTasks),
wg: &wg,
}
}
func (c *ConcurrencyHandler) Done() {
c.wg.Done()
}
func (c *ConcurrencyHandler) Wait() {
c.wg.Wait()
}
func (c *ConcurrencyHandler) Close() {
close(c.taskCh)
close(c.concurrencyCh)
}
type ConcurrencyTask struct {
f func()
idx int
ctx context.Context
cancel context.CancelFunc
}
func (c ConcurrencyTask) Ctx() context.Context {
return c.ctx
}
func (c ConcurrencyTask) Idx() int {
return c.idx
}
func (c *ConcurrencyTask) Cancel() {
c.cancel()
}
func (c *ConcurrencyHandler) Start() {
go func() {
for task := range c.taskCh {
c.concurrencyCh <- struct{}{}
go func(task ConcurrencyTask) {
select {
case <-task.ctx.Done():
break
default:
task.f()
}
c.Done()
<-c.concurrencyCh
}(task)
}
}()
}
func (c *ConcurrencyHandler) Enqueue(task func()) ConcurrencyTask {
c.curTaskIdx++
c.wg.Add(1)
ctx, cancel := context.WithCancel(context.Background())
cTask := ConcurrencyTask{
f: task,
idx: c.curTaskIdx,
ctx: ctx,
cancel: cancel,
}
c.taskCh <- cTask
return cTask
}