diff options
author | Luke Shumaker <lukeshu@lukeshu.com> | 2023-01-26 14:53:37 -0700 |
---|---|---|
committer | Luke Shumaker <lukeshu@lukeshu.com> | 2023-01-30 22:15:06 -0700 |
commit | 86063b41fc1a235930d6c79e6b7cd38ae8d8c147 (patch) | |
tree | 5c6b523a1c24062bbaba60bca1b7042b9976701c /lib/containers/syncvalue.go | |
parent | f4f062d7d4ed730411e04ecd36ee36387e50739c (diff) |
Split lib/containers.Sync* to git.lukeshu.com/go/typedsync
Diffstat (limited to 'lib/containers/syncvalue.go')
-rw-r--r-- | lib/containers/syncvalue.go | 67 |
1 files changed, 0 insertions, 67 deletions
diff --git a/lib/containers/syncvalue.go b/lib/containers/syncvalue.go deleted file mode 100644 index 160db3c..0000000 --- a/lib/containers/syncvalue.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) 2022-2023 Luke Shumaker <lukeshu@lukeshu.com> -// -// SPDX-License-Identifier: GPL-2.0-or-later - -package containers - -import ( - "sync" -) - -// SyncValue is a typed equivalent of sync/atomic.Value. -// -// It is not actually a wrapper around sync/atomic.Value for -// allocation-performance reasons. -type SyncValue[T comparable] struct { - mu sync.Mutex - ok bool - val T -} - -// This uses a dumb mutex-based solution because -// -// 1. Performance is good enough, because in the fast-path mutexes -// use the same compare-and-swap as sync/atomic.Value; and because -// all of these methods are short we're unlikely to hit the -// mutex's slow path. -// -// 2. We could use sync/atomic.Pointer[T], which by itself would have -// the same performance characteristics as sync/atomic.Value but -// without the benefit of runtime_procPin()/runtime_procUnpin(). -// We want to avoid that because it means we're doing an -// allocation for every store/swap; avoiding that is our whole -// reason for not just wraping sync/atomic.Value. So then we'd -// want to use a SyncPool to reuse allocations; but (1) that adds -// more sync-overhead, and (2) it also gets trickier because we'd -// have to be careful about not adding a pointer back to the pool -// when load has grabbed the pointer but not yet dereferenced it. - -func (v *SyncValue[T]) Load() (val T, ok bool) { - v.mu.Lock() - defer v.mu.Unlock() - return v.val, v.ok -} - -func (v *SyncValue[T]) Store(val T) { - v.mu.Lock() - defer v.mu.Unlock() - v.val, v.ok = val, true -} - -func (v *SyncValue[T]) Swap(newV T) (oldV T, oldOK bool) { - v.mu.Lock() - defer v.mu.Unlock() - oldV, oldOK = v.val, v.ok - v.val, v.ok = newV, true - return -} - -func (v *SyncValue[T]) CompareAndSwap(oldV, newV T) (swapped bool) { - v.mu.Lock() - defer v.mu.Unlock() - if !v.ok || v.val != oldV { - return false - } - v.val = newV - return true -} |