goext/syncext/atomic.go

35 lines
416 B
Go
Raw Permalink Normal View History

2022-11-30 23:35:47 +01:00
package syncext
2022-11-30 23:08:50 +01:00
2022-11-30 23:34:16 +01:00
import (
2023-01-29 22:28:08 +01:00
"sync"
2022-11-30 23:34:16 +01:00
)
2022-11-30 23:08:50 +01:00
2023-11-12 03:10:55 +01:00
type Atomic[T any] struct {
v T
lock sync.RWMutex
2022-11-30 23:08:50 +01:00
}
2023-11-12 03:10:55 +01:00
func NewAtomic[T any](value T) *Atomic[T] {
return &Atomic[T]{
v: value,
lock: sync.RWMutex{},
2022-11-30 23:08:50 +01:00
}
}
2023-11-12 03:10:55 +01:00
func (a *Atomic[T]) Get() T {
a.lock.RLock()
defer a.lock.RUnlock()
2023-01-29 22:28:08 +01:00
return a.v
2022-11-30 23:08:50 +01:00
}
2023-11-12 03:10:55 +01:00
func (a *Atomic[T]) Set(value T) T {
2023-01-29 22:28:08 +01:00
a.lock.Lock()
defer a.lock.Unlock()
oldValue := a.v
2023-01-29 22:28:08 +01:00
a.v = value
return oldValue
2022-11-30 23:34:16 +01:00
}