-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.go
102 lines (90 loc) · 2.12 KB
/
sync.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
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
package nstd
import (
"sync"
)
// Methods of *Mutex return a *Mutex result, so that
// these methods may be called in a chain.
// It is just a simpler wrapper of the [sync.Mutex].
// The main purpose of this type is to support
// the following use case:
//
// var aMutex nstd.Mutex
//
// func foo() {
// defer aMutex.Lock().Unlock()
// ... // do something
// }
type Mutex struct {
mu sync.Mutex
}
// Lock return m, so that the methods of m can be called in chain.
func (m *Mutex) Lock() *Mutex {
m.mu.Lock()
return m
}
// Unlock return m, so that the methods of m can be called in chain.
func (m *Mutex) Unlock() *Mutex {
m.mu.Unlock()
return m
}
// Do guards the execution of a function in Lock() and Unlock()
//
// See: https://github.com/golang/go/issues/63941
func (m *Mutex) Do(f func()) {
defer m.Lock().Unlock()
f()
}
// WaitGroup extends sync.WaitGroup.
// Each WaitGroup maintains an internal count which initial value is zero.
type WaitGroup struct {
wg sync.WaitGroup
}
// GoN starts several concurrent tasks and increases the internal count by len(fs).
// The internal count will be descreased by one when each of the task is done.
//
// See: https://github.com/golang/go/issues/18022
func (wg *WaitGroup) Go(fs ...func()) {
for i, f := range fs {
if f == nil {
Panicf("fs[%d] is nil", i)
}
}
wg.wg.Add(len(fs))
for _, f := range fs {
f := f
go func() {
defer wg.wg.Done()
f()
}()
}
}
// GoN starts a task n times concurrently and increases the internal count by n.
// The internal count will be descreased by one when each of the task instances is done.
func (wg *WaitGroup) GoN(n int, f func()) {
if n < 0 {
panic("the count must not be negative")
}
if f == nil {
panic("f is nil")
}
wg.wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.wg.Done()
f()
}()
}
}
// Wait blocks until the internal counter is zero.
func (wg *WaitGroup) Wait() {
wg.wg.Wait()
}
// WaitChannel returns a channel which reads will block until the internal counter is zero.
func (wg *WaitGroup) WaitChannel() <-chan struct{} {
var c = make(chan struct{})
go func() {
wg.wg.Wait()
close(c)
}()
return c
}