1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- package syncutils
- import "sync"
- type WriteVarFunc[T any] func(v T) T
- type ReadVarFunc[T any] func(v T)
- type SyncVar[T any] struct {
- writeLocker sync.Locker
- readLocker sync.Locker
- v T
- }
- func NewSyncVar[T any](v T, isRWMutex bool) *SyncVar[T] {
- var writeLocker sync.Locker
- var readLocker sync.Locker
- if !isRWMutex {
- mutex := &sync.Mutex{}
- writeLocker = mutex
- readLocker = mutex
- } else {
- mutex := &sync.RWMutex{}
- writeLocker = mutex
- readLocker = mutex.RLocker()
- }
- return &SyncVar[T]{
- writeLocker: writeLocker,
- readLocker: readLocker,
- v: v,
- }
- }
- func (syncVar *SyncVar[T]) ForWrite(writeVarFunc WriteVarFunc[T]) {
- if writeVarFunc == nil {
- return
- }
- syncVar.writeLocker.Lock()
- defer syncVar.writeLocker.Unlock()
- syncVar.v = writeVarFunc(syncVar.v)
- }
- func (syncVar *SyncVar[T]) ForRead(readVarFunc ReadVarFunc[T]) {
- if readVarFunc == nil {
- return
- }
- syncVar.readLocker.Lock()
- defer syncVar.readLocker.Unlock()
- readVarFunc(syncVar.v)
- }
|