forked from sspencer/colorart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
59 lines (47 loc) · 1.06 KB
/
utils.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
package colorart
import (
"runtime"
"sync/atomic"
)
type countedFn func(ch chan CountedSet, pmin, pmax int)
// parallelize data processing if 'enabled' is true
func parallelize(datamin, datamax int, fn countedFn) CountedSet {
datasize := datamax - datamin
partsize := datasize
numGoroutines := 1
numProcs := runtime.GOMAXPROCS(0)
if numProcs > 1 {
numGoroutines = numProcs
partsize = partsize / numGoroutines
if partsize < 1 {
partsize = 1
}
// if partsize had a fraction, bump it by 1 so entire image is covered
if partsize*numGoroutines < datasize {
partsize++
}
}
idx := int64(datamin)
ch := make(chan CountedSet, numGoroutines)
for p := 0; p < numGoroutines; p++ {
go func() {
for {
pmin := int(atomic.AddInt64(&idx, int64(partsize))) - partsize
if pmin >= datamax {
break
}
pmax := pmin + partsize
if pmax > datamax {
pmax = datamax
}
fn(ch, pmin, pmax)
}
}()
}
colors := NewCountedSet(10000)
for p := 0; p < numGoroutines; p++ {
colors.Merge(<-ch)
}
close(ch)
return colors
}