-
Notifications
You must be signed in to change notification settings - Fork 0
/
util-concurrency.go
71 lines (60 loc) · 1.04 KB
/
util-concurrency.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
/*
* Copyright (c) 2023.
* Created by Andy Pangaribuan <https://github.com/apangaribuan>.
* All Rights Reserved.
*/
package util
import (
"sync"
"time"
"github.com/andypangaribuan/project9/f9"
)
type srConcurrency struct {
mx sync.Mutex
max int
total int
active int
fn func(index int)
}
func (*srUtil) ConcurrentProcess(total, max int, fn func(index int)) {
c := &srConcurrency{
active: 0,
total: total,
max: max,
fn: fn,
}
c.start()
}
func (slf *srConcurrency) start() {
n := 0
for i := 0; i < slf.total; i++ {
if slf.active >= slf.max {
for {
time.Sleep(time.Millisecond * 10)
if slf.active < slf.max {
break
}
}
}
n++
slf.addActive(1)
idx := f9.Ptr(i)
go slf.execute(*idx)
}
for {
time.Sleep(time.Millisecond * 10)
if slf.active == 0 {
println("n: ", n)
break
}
}
}
func (slf *srConcurrency) execute(index int) {
slf.fn(index)
slf.addActive(-1)
}
func (slf *srConcurrency) addActive(add int) {
slf.mx.Lock()
defer slf.mx.Unlock()
slf.active += add
}