go-zero/core/syncx/atomicduration.go

37 lines
933 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
"sync/atomic"
"time"
)
2021-02-28 16:16:22 +08:00
// An AtomicDuration is an implementation of atomic duration.
2020-07-26 17:09:05 +08:00
type AtomicDuration int64
2021-02-28 16:16:22 +08:00
// NewAtomicDuration returns an AtomicDuration.
2020-07-26 17:09:05 +08:00
func NewAtomicDuration() *AtomicDuration {
return new(AtomicDuration)
}
2021-02-28 16:16:22 +08:00
// ForAtomicDuration returns an AtomicDuration with given value.
2020-07-26 17:09:05 +08:00
func ForAtomicDuration(val time.Duration) *AtomicDuration {
d := NewAtomicDuration()
d.Set(val)
return d
}
2021-02-28 16:16:22 +08:00
// CompareAndSwap compares current value with old, if equals, set the value to val.
2020-07-26 17:09:05 +08:00
func (d *AtomicDuration) CompareAndSwap(old, val time.Duration) bool {
return atomic.CompareAndSwapInt64((*int64)(d), int64(old), int64(val))
}
2021-02-28 16:16:22 +08:00
// Load loads the current duration.
2020-07-26 17:09:05 +08:00
func (d *AtomicDuration) Load() time.Duration {
return time.Duration(atomic.LoadInt64((*int64)(d)))
}
2021-02-28 16:16:22 +08:00
// Set sets the value to val.
2020-07-26 17:09:05 +08:00
func (d *AtomicDuration) Set(val time.Duration) {
atomic.StoreInt64((*int64)(d), int64(val))
}