Documentation
¶
Overview ¶
Package xsync implements some extra synchronization tools.
Index ¶
- Constants
- func CPUPause()
- func SendNoBlock[T any](c chan T, value T) (status int)
- func TrySend[T any](c chan T, value T) (ok bool)
- type DynamicWaitGroup
- type Latch
- type LatchWithValue
- type Lifecycle
- type Semaphore
- type SpinChan
- func (c *SpinChan[T]) Cap() int
- func (c *SpinChan[T]) Close()
- func (c *SpinChan[T]) IsClosed() bool
- func (c *SpinChan[T]) Len() int
- func (c *SpinChan[T]) Receive() (T, bool)
- func (c *SpinChan[T]) ReceiveWithCancel(cancel <-chan struct{}) (T, bool)
- func (c *SpinChan[T]) ReceiveWithSpin(pauseIters, yieldIters int, cancel <-chan struct{}) (T, bool)
- func (c *SpinChan[T]) Send(value T) bool
- func (c *SpinChan[T]) SendWithCancel(value T, cancel <-chan struct{}) bool
- func (c *SpinChan[T]) TryReceive() (T, bool)
- func (c *SpinChan[T]) TrySend(value T) bool
- func (c *SpinChan[T]) TrySendMany(value T, count int) int
- func (c *SpinChan[T]) WithCancel(cancel <-chan struct{}) *SpinChan[T]
- func (c *SpinChan[T]) WithPauseIters(iters int) *SpinChan[T]
- func (c *SpinChan[T]) WithShouldSpin(fn func() bool) *SpinChan[T]
- func (c *SpinChan[T]) WithYieldIters(iters int) *SpinChan[T]
- type SyncMap
- func (m *SyncMap[K, V]) Clear()
- func (m *SyncMap[K, V]) Delete(key K)
- func (m *SyncMap[K, V]) Load(key K) (value V, ok bool)
- func (m *SyncMap[K, V]) LoadAndDelete(key K) (value V, loaded bool)
- func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool)
- func (m *SyncMap[K, V]) Range(f func(key K, value V) bool)
- func (m *SyncMap[K, V]) Store(key K, value V)
- type WeakHandle
- type WeakTracker
Constants ¶
const ( // DefaultSpinEnabled reports whether adaptive spin-waiting is recommended by default on // this architecture. Enabled on amd64 where homogeneous cores and hardware PAUSE make // tight spinning a consistent win on parallel fan-out workloads. DefaultSpinEnabled = true // DefaultSpinPauseIters is the default number of tight PAUSE iterations (~5-8 ns each on // Zen 5, ~40-60 µs total) performed while polling before yielding. DefaultSpinPauseIters = 8000 // DefaultSpinYieldIters is the default number of cooperative runtime.Gosched() iterations // executed after tight spinning expires and before parking at 0% CPU. DefaultSpinYieldIters = 4 )
Variables ¶
This section is empty.
Functions ¶
func CPUPause ¶ added in v0.1.38
func CPUPause()
CPUPause executes the x86 PAUSE instruction, hinting to the CPU that the thread is in a spin-wait loop. This avoids memory-order pipeline flushes when the watched atomic changes, reduces power consumption, and yields execution resources to any SMT sibling thread.
func SendNoBlock ¶
SendNoBlock tries to send a value through the channel.
It returns 0 if the value was sent, 1 if sending it blocks (channel buffer full) or 2 if the channel `c` was closed.
Types ¶
type DynamicWaitGroup ¶
type DynamicWaitGroup struct {
// contains filtered or unexported fields
}
DynamicWaitGroup is a WaitGroup-like synchronization primitive that allows the count to be changed (new values added) while someone is waiting for it.
It uses sync.Cond to coordinate changes.
func NewDynamicWaitGroup ¶
func NewDynamicWaitGroup() *DynamicWaitGroup
NewDynamicWaitGroup creates a new DynamicWaitGroup.
func (*DynamicWaitGroup) Add ¶
func (cwg *DynamicWaitGroup) Add(delta int)
Add changes the DynamicWaitGroup counter by the given delta. If the counter becomes zero, it broadcasts to all waiting goroutines. If the counter would go negative, it panics.
func (*DynamicWaitGroup) Done ¶
func (cwg *DynamicWaitGroup) Done()
Done decrements the DynamicWaitGroup counter by one. This is a convenience wrapper around Add(-1).
func (*DynamicWaitGroup) Wait ¶
func (cwg *DynamicWaitGroup) Wait()
Wait blocks until the DynamicWaitGroup counter is zero.
type Latch ¶
type Latch struct {
// contains filtered or unexported fields
}
Latch implements a "latch" synchronization mechanism.
A Latch is a signal that can be waited for until it is triggered. Once triggered, it never changes state, it's forever triggered.
type LatchWithValue ¶
type LatchWithValue[T any] struct { // contains filtered or unexported fields }
LatchWithValue implements a "latch" synchronization mechanism with a value associated with the triggering of the latch.
A LatchWithValue is a signal that can be waited for until it is triggered. Once triggered, it never changes state, it's forever triggered.
func NewLatchWithValue ¶
func NewLatchWithValue[T any]() *LatchWithValue[T]
NewLatchWithValue returns an un-triggered latch.
func (*LatchWithValue[T]) Test ¶
func (l *LatchWithValue[T]) Test() bool
Test checks whether the latch has been triggered.
func (*LatchWithValue[T]) Trigger ¶
func (l *LatchWithValue[T]) Trigger(value T)
Trigger latch and saves the associated value.
func (*LatchWithValue[T]) Wait ¶
func (l *LatchWithValue[T]) Wait() T
Wait waits for the latch to be triggered.
type Lifecycle ¶ added in v0.1.33
type Lifecycle struct {
// contains filtered or unexported fields
}
Lifecycle coordinates concurrent operations against an idempotent Finalize teardown.
In-flight operations call Enter/Leave (acquiring a shared RWMutex read lock), while Finalize acquires the exclusive write lock, waiting for all in-flight operations to finish before running the teardown callback exactly once.
Zero value is ready to use. Must not be copied after first use.
IMPORTANT: Go's sync.RWMutex is not reentrant. Never call Enter() again on the same goroutine before calling Leave(), or a concurrent Finalize() waiting on Lock() will deadlock.
func (*Lifecycle) Enter ¶ added in v0.1.33
Enter acquires a shared read lock for an in-flight operation.
If Finalize has already been called, Enter returns false without holding any lock. If Enter returns true, the caller MUST call Leave exactly once when the operation finishes.
Do not call Enter reentrantly from a goroutine that already holds Enter.
func (*Lifecycle) Finalize ¶ added in v0.1.33
func (l *Lifecycle) Finalize(teardown func())
Finalize waits for all in-flight Enter/Leave pairs to complete, marks the lifecycle as finalized, and invokes teardown exactly once while holding the exclusive write lock.
Concurrent callers to Finalize block until teardown completes and then return without invoking teardown again.
func (*Lifecycle) IsFinalized ¶ added in v0.1.33
IsFinalized reports whether Finalize has started or completed. It is lock-free and safe to call concurrently from any goroutine.
type Semaphore ¶
type Semaphore struct {
// contains filtered or unexported fields
}
Semaphore that allows dynamic resizing.
It uses a sync.Cond to allow dynamic resizing, so it will be slower than a pure channel semaphore version with a fixed capacity. This shouldn't matter for more coarse resource control.
func NewSemaphore ¶
NewSemaphore returns a Semaphore that allows at most capacity simultaneous acquisitions. If capacity <= 0, there is no limit on acquisitions.
FIFO ordering may be lost during resizes (Semaphore.Resize) to larger capacity, but otherwise it is respected.
func (*Semaphore) Acquire ¶
func (s *Semaphore) Acquire()
Acquire resource observing current semaphore capacity. It must be matched by exactly one call to Semaphore.Release after the reservation is no longer needed.
func (*Semaphore) Release ¶
func (s *Semaphore) Release()
Release resource previously allocated with Semaphore.Acquire.
func (*Semaphore) Resize ¶
Resize the number of available resources in the Semaphore.
If the newCapacity is larger than the previous one, this may immediately allow pending Semaphore.Acquire to proceed. Notice since all waiting Semaphore.Acquire are awoken (broadcast), the queue order may be lost.
If the newCapacity is smaller than the previous one, it doesn't have any effect on current acquisitions. So if the Semaphore is being used to control a worker pool, reducing its size won't stop workers currently executing.
func (*Semaphore) TryAcquire ¶
TryAcquire tries to acquire resource without blocking. It returns true if the resource was acquired, false if the semaphore is full.
If acquisition was successful (returned true), the caller must call Semaphore.Release.
type SpinChan ¶ added in v0.1.38
type SpinChan[T any] struct { // contains filtered or unexported fields }
SpinChan is a bounded, lock-free multi-producer multi-consumer (MPMC) channel with adaptive three-phase spin-before-park receiving.
Compared to Go's built-in chan, SpinChan avoids OS futex sleep/wakeup latency (~15-25 µs) when producers and consumers exchange bursts of work separated by short gaps (e.g., 10-40 µs between consecutive neural-network ops):
- Tight spin (pauseIters iterations of CPUPause()): Receivers poll the lock-free ring buffer with hardware spin-wait hints (PAUSE on amd64, ISB on arm64), observing new items in ~100-300 ns with zero mutexes and zero syscalls.
- Cooperative yield (yieldIters iterations of runtime.Gosched()): Briefly yields the Go processor so GC or other goroutines make progress.
- Park (0% CPU): Parks on a per-waiter channel (LIFO wakeup order for warmer CPU caches) and supports immediate wake on Close() or an external cancellation channel with zero goroutine leaks.
Configure optional parameters using the builder methods before sharing the channel:
ch := xsync.NewSpinChan[func()](1024).
WithPauseIters(4000).
WithYieldIters(4).
WithShouldSpin(pred).
WithCancel(ctx.Done())
func NewSpinChan ¶ added in v0.1.38
NewSpinChan creates a new SpinChan with at least the requested buffer capacity (rounded up to the next power of 2, minimum 2).
By default, pauseIters is DefaultSpinPauseIters and yieldIters is DefaultSpinYieldIters. Use WithPauseIters / WithYieldIters / WithShouldSpin / WithCancel to customize behavior before sharing the channel across goroutines.
func (*SpinChan[T]) Cap ¶ added in v0.1.38
Cap returns the buffer capacity of the channel (always a power of 2 >= 2).
func (*SpinChan[T]) Close ¶ added in v0.1.38
func (c *SpinChan[T]) Close()
Close closes the channel and wakes all parked receivers and senders. Safe to call multiple times concurrently. Subsequent Send/TrySend calls return false; receivers continue draining any buffered items before returning (zero, false).
func (*SpinChan[T]) IsClosed ¶ added in v0.1.38
IsClosed reports whether Close() has been called on the channel.
func (*SpinChan[T]) Len ¶ added in v0.1.38
Len returns an approximate count of items currently buffered in the channel.
func (*SpinChan[T]) Receive ¶ added in v0.1.38
Receive blocks until an item is available, the channel is closed and drained, or the channel's cancel channel closes. Uses the spin/yield budget configured via WithPauseIters / WithYieldIters / WithShouldSpin.
func (*SpinChan[T]) ReceiveWithCancel ¶ added in v0.1.38
ReceiveWithCancel is like Receive, also aborting and returning (zero, false) if cancel closes.
func (*SpinChan[T]) ReceiveWithSpin ¶ added in v0.1.38
ReceiveWithSpin receives one item using an explicit per-call spin/yield budget and optional per-call cancellation channel (combined with any channel-wide WithCancel). Passing pauseIters=0, yieldIters=0 skips spinning and parks immediately when empty.
func (*SpinChan[T]) Send ¶ added in v0.1.38
Send enqueues value, blocking if the buffer is full until space becomes available, the channel is closed, or the channel's cancel channel closes. Returns true if value was enqueued, or false if closed or cancelled.
func (*SpinChan[T]) SendWithCancel ¶ added in v0.1.38
SendWithCancel is like Send, also aborting and returning false if cancel is closed.
func (*SpinChan[T]) TryReceive ¶ added in v0.1.38
TryReceive attempts to dequeue one item without spinning or blocking. Returns (value, true) if an item was received, or (zero, false) if currently empty.
func (*SpinChan[T]) TrySend ¶ added in v0.1.38
TrySend attempts to enqueue value without blocking. Returns true if value was enqueued, or false if the channel is full, closed, or cancelled.
func (*SpinChan[T]) TrySendMany ¶ added in v0.1.38
TrySendMany atomically enqueues up to count copies of value without blocking, using a single tail CAS and a single receiver wake check. Returns the number of copies actually enqueued (0 if count <= 0, full, closed, or cancelled).
func (*SpinChan[T]) WithCancel ¶ added in v0.1.38
WithCancel attaches an external cancellation channel (such as ctx.Done() or Latch.WaitChan()). When cancel is closed, blocked or spinning Send/Receive calls abort promptly and return false. Must be called before sharing the channel across goroutines.
func (*SpinChan[T]) WithPauseIters ¶ added in v0.1.38
WithPauseIters configures the number of hardware CPUPause() iterations a receiver performs before yielding. Passing 0 disables tight hardware spinning. Must be called before sharing the channel across goroutines.
func (*SpinChan[T]) WithShouldSpin ¶ added in v0.1.38
WithShouldSpin configures an optional predicate consulted before a receiver enters the spin/yield phases. When fn returns false, receivers park immediately at 0% CPU without spinning (e.g., when no computation is currently active). Must be called before sharing the channel across goroutines.
func (*SpinChan[T]) WithYieldIters ¶ added in v0.1.38
WithYieldIters configures the number of cooperative runtime.Gosched() iterations a receiver performs after tight spinning and before parking at 0% CPU. Must be called before sharing the channel across goroutines.
type SyncMap ¶
type SyncMap[K comparable, V any] struct { Map sync.Map }
SyncMap is a trivial wrapper to sync.Map that casts the key and value types accordingly.
As sync.Map, it can be created ready to go but should not be copied once it is used.
func (*SyncMap[K, V]) Clear ¶
func (m *SyncMap[K, V]) Clear()
Clear removes all key-value pairs from the map.
func (*SyncMap[K, V]) Delete ¶
func (m *SyncMap[K, V]) Delete(key K)
Delete deletes the value for a key.
func (*SyncMap[K, V]) Load ¶
Load returns the value stored in the map for a key or nil if no value is present. The ok result indicates whether a value was found in the map.
func (*SyncMap[K, V]) LoadAndDelete ¶
LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.
func (*SyncMap[K, V]) LoadOrStore ¶
LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.
type WeakHandle ¶ added in v0.1.33
type WeakHandle[T any] struct { // contains filtered or unexported fields }
WeakHandle represents a tracked registration in a WeakTracker. Calling Untrack on a nil handle or multiple times is a safe no-op.
func (*WeakHandle[T]) Untrack ¶ added in v0.1.33
func (h *WeakHandle[T]) Untrack()
Untrack removes the object from its WeakTracker and cancels its GC cleanup. Safe to call concurrently, multiple times, or on a nil handle.
type WeakTracker ¶ added in v0.1.33
type WeakTracker[T any] struct { // contains filtered or unexported fields }
WeakTracker tracks live objects of type *T without preventing them from being garbage-collected.
Intended for low-frequency objects such as compiled Executables and Builders (NOT hot-path Buffers). Tracked objects are automatically removed from the tracker if garbage-collected before Untrack is called.
Zero value is ready to use. Must not be copied after first use.
func (*WeakTracker[T]) Drain ¶ added in v0.1.33
func (t *WeakTracker[T]) Drain() []*T
Drain marks the tracker closed, clears all entries, and returns strong pointers to all currently reachable tracked objects (omitting any already collected by GC).
Drain releases the tracker's mutex before returning so callers can safely finalize each returned object (which may call Untrack) without risking deadlocks.
func (*WeakTracker[T]) Len ¶ added in v0.1.33
func (t *WeakTracker[T]) Len() int
Len returns the current number of entries in the tracker (including any not yet pruned by GC cleanup).
func (*WeakTracker[T]) Track ¶ added in v0.1.33
func (t *WeakTracker[T]) Track(obj *T) *WeakHandle[T]
Track registers obj in the tracker and returns a handle that should be passed to Untrack when obj is explicitly finalized.
If obj is nil or the tracker has already been drained, Track returns nil.