Skip to content

Commit

Permalink
feat(sync): add some scope methods
Browse files Browse the repository at this point in the history
Change-Id: I4be6e3a53d713d3d87dbea173ab214f753927624
  • Loading branch information
andeya committed Jan 9, 2023
1 parent f233c60 commit 032a2e3
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,21 @@ func (m *Mutex[T]) Unlock(newData ...T) {
m.inner.Unlock()
}

// LockScope securely read and write the data in the mutex.
func (m *Mutex[T]) LockScope(f func(T) T) {
m.inner.Lock()
defer m.inner.Unlock()
m.data = f(m.data)
}

// TryLockScope tries to securely read and write the data in the mutex.
func (m *Mutex[T]) TryLockScope(f func(T) T) {
if m.inner.TryLock() {
defer m.inner.Unlock()
m.data = f(m.data)
}
}

// RWMutex is a better generic-type wrapper for `sync.RWMutex` that holds a value.
// A RWMutex is a reader/writer mutual exclusion lock.
// The lock can be held by an arbitrary number of readers or a single writer.
Expand Down Expand Up @@ -123,6 +138,21 @@ func (m *RWMutex[T]) Unlock(newData ...T) {
m.inner.Unlock()
}

// TryLockScope tries to securely read and write the data in the mutex.
func (m *RWMutex[T]) TryLockScope(f func(T) T) {
if m.inner.TryLock() {
defer m.inner.Unlock()
m.data = f(m.data)
}
}

// LockScope securely read and write the data in the rwmutex.
func (m *RWMutex[T]) LockScope(f func(T) T) {
m.inner.Lock()
defer m.inner.Unlock()
m.data = f(m.data)
}

// Happens-before relationships are indicated to the race detector via:
// - Unlock -> Lock: readerSem
// - Unlock -> RLock: readerSem
Expand Down Expand Up @@ -166,6 +196,21 @@ func (m *RWMutex[T]) RUnlock() {
m.inner.RUnlock()
}

// TryRLockScope tries to securely read the data in the mutex.
func (m *RWMutex[T]) TryRLockScope(f func(T) T) {
if m.inner.TryRLock() {
defer m.inner.RUnlock()
m.data = f(m.data)
}
}

// RLockScope securely read the data in the rwmutex.
func (m *RWMutex[T]) RLockScope(f func(T) T) {
m.inner.RLock()
defer m.inner.RUnlock()
m.data = f(m.data)
}

// SyncMap is a better generic-type wrapper for `sync.Map`.
// A SyncMap is like a Go map[interface{}]interface{} but is safe for concurrent use
// by multiple goroutines without additional locking or coordination.
Expand Down

0 comments on commit 032a2e3

Please sign in to comment.