-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync.go
60 lines (53 loc) · 828 Bytes
/
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
package po
import (
"sync"
"sync/atomic"
)
type Once struct {
done uint32
doneM sync.Mutex
doneC chan struct{}
doneCM sync.Mutex
err error
}
func (o *Once) Do(f func()) {
if atomic.LoadUint32(&o.done) == 0 {
o.doSlow(f)
}
}
func (o *Once) ErrorDo(f func() error) error {
o.Do(func() {
o.err = f()
})
return o.err
}
func (o *Once) Wait() <-chan struct{} {
o.doneCM.Lock()
defer o.doneCM.Unlock()
if o.doneC == nil {
o.doneC = make(chan struct{})
}
if o.Done() {
select {
case <-o.doneC:
default:
close(o.doneC)
}
}
return o.doneC
}
func (o *Once) Done() bool {
return atomic.LoadUint32(&o.done) == 1
}
func (o *Once) doSlow(f func()) {
o.doneM.Lock()
defer o.doneM.Unlock()
if o.done == 1 {
return
}
defer func() {
atomic.StoreUint32(&o.done, 1)
o.Wait()
}()
f()
}