atomicint.go 944 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package atomic
  2. import "sync/atomic"
  3. type AtomicInt32 int32
  4. // NewAtomicInt32 creates a new atomic int32 instance.
  5. func NewAtomicInt32(value int32) *AtomicInt32 {
  6. ai := new(AtomicInt32)
  7. ai.Set(value)
  8. return ai
  9. }
  10. // Loads the int32 value atomically
  11. func (ai *AtomicInt32) Get() int32 {
  12. return atomic.LoadInt32((*int32)(ai))
  13. }
  14. // Sets the int32 value atomically
  15. func (ai *AtomicInt32) Set(value int32) {
  16. atomic.StoreInt32((*int32)(ai), value)
  17. }
  18. // Increments the atomic int and returns the new value
  19. func (ai *AtomicInt32) Increment() int32 {
  20. return atomic.AddInt32((*int32)(ai), 1)
  21. }
  22. // Decrements the atomint int and returns the new value
  23. func (ai *AtomicInt32) Decrement() int32 {
  24. return atomic.AddInt32((*int32)(ai), -1)
  25. }
  26. // CompareAndSet sets value to new if current is equal to the current value
  27. func (ai *AtomicInt32) CompareAndSet(current, new int32) bool {
  28. return atomic.CompareAndSwapInt32((*int32)(ai), current, new)
  29. }