atomicduration.go 933 B

123456789101112131415161718192021222324252627282930313233343536
  1. package syncx
  2. import (
  3. "sync/atomic"
  4. "time"
  5. )
  6. // An AtomicDuration is an implementation of atomic duration.
  7. type AtomicDuration int64
  8. // NewAtomicDuration returns an AtomicDuration.
  9. func NewAtomicDuration() *AtomicDuration {
  10. return new(AtomicDuration)
  11. }
  12. // ForAtomicDuration returns an AtomicDuration with given value.
  13. func ForAtomicDuration(val time.Duration) *AtomicDuration {
  14. d := NewAtomicDuration()
  15. d.Set(val)
  16. return d
  17. }
  18. // CompareAndSwap compares current value with old, if equals, set the value to val.
  19. func (d *AtomicDuration) CompareAndSwap(old, val time.Duration) bool {
  20. return atomic.CompareAndSwapInt64((*int64)(d), int64(old), int64(val))
  21. }
  22. // Load loads the current duration.
  23. func (d *AtomicDuration) Load() time.Duration {
  24. return time.Duration(atomic.LoadInt64((*int64)(d)))
  25. }
  26. // Set sets the value to val.
  27. func (d *AtomicDuration) Set(val time.Duration) {
  28. atomic.StoreInt64((*int64)(d), int64(val))
  29. }