-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.go
More file actions
105 lines (89 loc) · 1.67 KB
/
sync.go
File metadata and controls
105 lines (89 loc) · 1.67 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// SPDX-FileCopyrightText: 2025 Dominik Honnef and contributors
//
// SPDX-License-Identifier: MIT
package syncutil
import (
"runtime"
"slices"
"sync"
)
func Map[S ~[]E, E, R any](items S, limit int, out []R, fn func(subitems S) (R, error)) ([]R, error) {
if len(items) == 0 {
return nil, nil
}
if limit <= 0 {
limit = runtime.GOMAXPROCS(0)
}
if limit > len(items) {
limit = len(items)
}
out = slices.Grow(out, limit)[:len(out)+limit]
err := Distribute(items, limit, func(group int, step int, subitems S) error {
res, err := fn(subitems)
out[group] = res
return err
})
return out, err
}
func Distribute[S ~[]E, E any](items S, limit int, fn func(group int, step int, subitems S) error) error {
if len(items) == 0 {
return nil
}
if limit <= 0 {
limit = runtime.GOMAXPROCS(0)
}
if limit > len(items) {
limit = len(items)
}
step := len(items) / limit
var muGerr sync.Mutex
var gerr error
var wg sync.WaitGroup
wg.Add(limit)
for g := range limit {
go func() {
defer wg.Done()
var subset S
if g < limit-1 {
subset = items[g*step : (g+1)*step]
} else {
subset = items[g*step:]
}
if err := fn(g, step, subset); err != nil {
muGerr.Lock()
if gerr == nil {
gerr = err
}
muGerr.Unlock()
}
}()
}
wg.Wait()
return gerr
}
type Pool[T any] struct {
pool sync.Pool
}
func NewPool[T any](fn func() T) *Pool[T] {
return &Pool[T]{
pool: sync.Pool{
New: func() any {
return fn()
},
},
}
}
func (p *Pool[T]) Put(v T) {
p.pool.Put(v)
}
func (p *Pool[T]) Get() T {
return p.pool.Get().(T)
}
func TryRecv[T any](ch <-chan T) bool {
select {
case <-ch:
return true
default:
return false
}
}