-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecutor_queue.go
More file actions
87 lines (78 loc) · 1.53 KB
/
Copy pathexecutor_queue.go
File metadata and controls
87 lines (78 loc) · 1.53 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
package sync
import (
"context"
"sync"
"sync/atomic"
)
// queuedExecutor is an Executor that accepts units of work to execute asynchronously, queuing them rather than blocking
type queuedExecutor struct {
canceled atomic.Bool
maxConcurrency int
executing atomic.Int32
queue List[*func()]
wg sync.WaitGroup
childLock sync.RWMutex
childExecutor *errGroupExecutor
}
var _ Executor = (*queuedExecutor)(nil)
func (e *queuedExecutor) Go(f func()) {
if e.canceled.Load() {
return
}
e.wg.Add(1)
fn := func() {
defer e.wg.Done()
if e.canceled.Load() {
return
}
f()
}
e.queue.Enqueue(&fn)
if int(e.executing.Load()) < e.maxConcurrency {
go e.exec()
}
}
func (e *queuedExecutor) Wait(ctx context.Context) {
e.canceled.Store(ctx.Err() != nil)
done := make(chan struct{})
go func() {
e.wg.Wait()
close(done)
}()
select {
case <-ctx.Done():
e.canceled.Store(true)
case <-done:
}
}
func (e *queuedExecutor) ChildExecutor() Executor {
e.childLock.RLock()
child := e.childExecutor
e.childLock.RUnlock()
if child != nil {
return child
}
e.childLock.Lock()
defer e.childLock.Unlock()
if e.childExecutor == nil {
// create child executor with same bound
e.childExecutor = newErrGroupExecutor(e.maxConcurrency)
}
return e.childExecutor
}
func (e *queuedExecutor) exec() {
e.executing.Add(1)
defer e.executing.Add(-1)
if int(e.executing.Load()) > e.maxConcurrency {
return
}
for {
f, ok := e.queue.Dequeue()
if !ok {
return
}
if f != nil {
(*f)()
}
}
}