forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atomicduration.go
36 lines (29 loc) · 933 Bytes
/
atomicduration.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
package syncx
import (
"sync/atomic"
"time"
)
// An AtomicDuration is an implementation of atomic duration.
type AtomicDuration int64
// NewAtomicDuration returns an AtomicDuration.
func NewAtomicDuration() *AtomicDuration {
return new(AtomicDuration)
}
// ForAtomicDuration returns an AtomicDuration with given value.
func ForAtomicDuration(val time.Duration) *AtomicDuration {
d := NewAtomicDuration()
d.Set(val)
return d
}
// CompareAndSwap compares current value with old, if equals, set the value to val.
func (d *AtomicDuration) CompareAndSwap(old, val time.Duration) bool {
return atomic.CompareAndSwapInt64((*int64)(d), int64(old), int64(val))
}
// Load loads the current duration.
func (d *AtomicDuration) Load() time.Duration {
return time.Duration(atomic.LoadInt64((*int64)(d)))
}
// Set sets the value to val.
func (d *AtomicDuration) Set(val time.Duration) {
atomic.StoreInt64((*int64)(d), int64(val))
}