generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
once.go
47 lines (39 loc) 路 823 Bytes
/
once.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
package cosyne
import (
"context"
"sync/atomic"
)
// Once is a context-aware and "failable" version of sync.Once.
type Once struct {
done uint32 // atomic bool
m Mutex
}
// Do calls the function fn if and only if Do() has never been called
// successfully for this instance of Once.
//
// A successful call is one that returns a nil error and does not panic.
func (o *Once) Do(
ctx context.Context,
fn func(context.Context) error,
) error {
if atomic.LoadUint32(&o.done) == 0 {
return o.doSlow(ctx, fn)
}
return nil
}
func (o *Once) doSlow(
ctx context.Context,
fn func(context.Context) error,
) error {
if err := o.m.Lock(ctx); err != nil {
return err
}
defer o.m.Unlock()
if o.done == 0 {
if err := fn(ctx); err != nil {
return err
}
atomic.StoreUint32(&o.done, 1)
}
return nil
}