-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsyncmanager.go
More file actions
70 lines (55 loc) · 1.14 KB
/
syncmanager.go
File metadata and controls
70 lines (55 loc) · 1.14 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
package syncmanager
func NewSyncManager(concurrent int) *SyncManager {
if concurrent < 1 {
concurrent = 1
}
syncManager := new(SyncManager)
syncManager.concurrent = concurrent
syncManager.addQueue = make(chan struct{})
syncManager.doneQueue = make(chan struct{})
syncManager.exitCh = make(chan struct{})
go syncManager.daemon()
return syncManager
}
type SyncManager struct {
QueueList []*Queue
addQueue chan struct{}
doneQueue chan struct{}
exitCh chan struct{}
concurrent int
isWaiting bool
}
func (s *SyncManager) Add(f func(...any), args ...any) {
s.QueueList = append(s.QueueList, &Queue{
Func: f,
Args: args,
})
s.addQueue <- struct{}{}
}
func (s *SyncManager) Wait() {
s.isWaiting = true
<-s.exitCh
}
func (s *SyncManager) daemon() {
var running int
for {
select {
case <-s.addQueue:
case <-s.doneQueue:
running--
}
if running < s.concurrent && len(s.QueueList) != 0 {
queue := s.QueueList[0]
s.QueueList = s.QueueList[1:]
go func() {
queue.Func(queue.Args...)
s.doneQueue <- struct{}{}
}()
running++
}
if s.isWaiting && running == 0 {
close(s.exitCh)
break
}
}
}