Documentation
¶
Overview ¶
Package ossync provides zero-cgo Go bindings for Darwin's futex-equivalent wait-on-address primitives (os_sync_wait_on_address, macOS 14.4+) and os_unfair_lock, along with a lock-free cross-process Ring over shared memory.
All blocking wait operations pin the calling goroutine with runtime.LockOSThread so thread-local errno can be read accurately via __error() and classified into ErrTimeout, ErrInterrupted, ErrFault, or ErrInvalid.
Pass Local when synchronizing threads within a single process, or Shared when synchronizing across processes over a shared mmap region. The same Flags value and word size (4 or 8 bytes) must be used for matching wait and wake calls on an address.
Basic usage:
var state uint32
go func() {
atomic.StoreUint32(&state, 1)
_ = ossync.WakeOne(&state, ossync.Local)
}()
for atomic.LoadUint32(&state) == 0 {
if err := ossync.WaitUint32(&state, 0, ossync.Local); err != nil && !errors.Is(err, ossync.ErrInterrupted) {
log.Fatal(err)
}
}
Example ¶
package main
import (
"errors"
"fmt"
"sync/atomic"
"github.com/tmc/apple/x/ossync"
)
func main() {
var state uint32
go func() {
atomic.StoreUint32(&state, 1)
_ = ossync.WakeOne(&state, ossync.Local)
}()
for atomic.LoadUint32(&state) == 0 {
err := ossync.WaitUint32(&state, 0, ossync.Local)
if err != nil && !errors.Is(err, ossync.ErrInterrupted) {
panic(err)
}
}
fmt.Println("state:", atomic.LoadUint32(&state))
}
Output: state: 1
Index ¶
- Constants
- Variables
- func RingSize(capacity, slotSize int) int
- func WaitTimeout[T Word](addr *T, expected T, timeout time.Duration, flags Flags) error
- func WaitUint32(addr *uint32, expected uint32, flags Flags) error
- func WaitUint64(addr *uint64, expected uint64, flags Flags) error
- func WakeAll[T Word](addr *T, flags Flags) error
- func WakeOne[T Word](addr *T, flags Flags) error
- type Flags
- type Ring
- func (r *Ring) Capacity() int
- func (r *Ring) Flags() Flags
- func (r *Ring) Len() int
- func (r *Ring) Pop(dst []byte) error
- func (r *Ring) PopTimeout(dst []byte, timeout time.Duration) error
- func (r *Ring) Push(src []byte) error
- func (r *Ring) PushTimeout(src []byte, timeout time.Duration) error
- func (r *Ring) SlotSize() int
- func (r *Ring) TryPop(dst []byte) (bool, error)
- func (r *Ring) TryPush(src []byte) (bool, error)
- type UnfairLock
- type Word
Examples ¶
Constants ¶
const ( // RingHeaderSize is the byte size of the cache-line-padded control header // preceding the slot data in a [Ring] backing slice. // // Layout (128-byte cache-line separation for Apple Silicon): // [0..128) immutable metadata: magic, version, capacity, slotSize, flags // [128..256) producer cache line: head (uint32), prodWait (uint32) // [256..384) consumer cache line: tail (uint32), consWait (uint32) // [384..) capacity * slotSize bytes of slot storage RingHeaderSize = 384 )
Variables ¶
var ( // ErrTimeout reports that a timed wait expired (ETIMEDOUT). ErrTimeout = errors.New("ossync: wait timed out") // ErrInterrupted reports that a wait returned early due to a signal or // spurious wakeup (EINTR). Callers should re-check the guarded value // before retrying. ErrInterrupted = errors.New("ossync: wait interrupted") // ErrFault reports that the kernel could not read the wait address (EFAULT). ErrFault = errors.New("ossync: address fault") // ErrInvalid reports an invalid argument such as a nil or misaligned // address, non-positive timeout, invalid ring parameters, or mismatched // wait/wake flags (EINVAL). ErrInvalid = errors.New("ossync: invalid argument") // ErrUnsupported reports that required Darwin synchronization symbols // are unavailable on this macOS version (os_sync_wait_on_address requires // macOS 14.4 or later). ErrUnsupported = errors.New("ossync: unsupported on this system") )
Functions ¶
func RingSize ¶
RingSize returns the total backing buffer size in bytes required for a Ring with the given power-of-two capacity and slotSize, or 0 if the parameters are invalid.
func WaitTimeout ¶
WaitTimeout atomically compares *addr with expected and blocks until woken, until *addr differs from expected, or until timeout elapses.
If timeout expires before a wake, WaitTimeout returns an error wrapping ErrTimeout and syscall.ETIMEDOUT. A non-positive timeout returns ErrInvalid.
func WaitUint32 ¶
WaitUint32 atomically compares *addr with expected and blocks the calling goroutine until woken by WakeOne or WakeAll, or until *addr differs from expected.
It returns nil on a wake or value mismatch, or an error wrapping ErrInterrupted, ErrFault, ErrInvalid, or ErrUnsupported.
func WaitUint64 ¶
WaitUint64 atomically compares *addr with expected and blocks the calling goroutine until woken by WakeOne or WakeAll, or until *addr differs from expected.
It returns nil on a wake or value mismatch, or an error wrapping ErrInterrupted, ErrFault, ErrInvalid, or ErrUnsupported.
Types ¶
type Flags ¶
type Flags uint32
Flags controls whether wait and wake operations apply to a single process or to shared memory mapped into multiple processes.
const ( // Local restricts wait/wake to threads in the current process. Local Flags = Flags(os.OSSyncWaitOnAddressNone) // memory mapping (such as MAP_SHARED mmap). Shared Flags = Flags(os.OSSyncWaitOnAddressShared) )
type Ring ¶
type Ring struct {
// contains filtered or unexported fields
}
Ring is a lock-free single-producer, single-consumer (SPSC) ring buffer over a caller-supplied byte slice, using Darwin wait-on-address (WaitUint32, WaitTimeout, WakeOne) for blocking when empty or full.
When backed by a shared mmap region and initialized with Shared, one process may call InitRing and push items while another process calls OpenRing on the same mapping and pops items with zero copies through the kernel.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/ossync"
)
func main() {
buf := make([]byte, ossync.RingSize(8, 16))
prod, err := ossync.InitRing(buf, 8, 16, ossync.Local)
if err != nil {
panic(err)
}
cons, err := ossync.OpenRing(buf)
if err != nil {
panic(err)
}
msg := []byte("hello-ossync-shm")
if err := prod.Push(msg); err != nil {
panic(err)
}
got := make([]byte, 16)
if err := cons.Pop(got); err != nil {
panic(err)
}
fmt.Println(string(got))
}
Output: hello-ossync-shm
func InitRing ¶
InitRing initializes a new Ring in buf with the given power-of-two capacity (at least 2) and fixed slotSize in bytes. buf must be at least RingSize(capacity, slotSize) bytes long and 4-byte aligned.
func OpenRing ¶
OpenRing attaches to an existing Ring previously initialized in buf by InitRing (potentially in another process sharing the same mmap).
func (*Ring) Pop ¶
Pop reads the next queued slot into dst, blocking until an item is available. len(dst) must equal Ring.SlotSize.
func (*Ring) PopTimeout ¶
PopTimeout reads the next queued slot into dst, blocking up to timeout if the ring is empty. It returns an error wrapping ErrTimeout and syscall.ETIMEDOUT if timeout elapses before an item arrives.
func (*Ring) Push ¶
Push writes src into the ring, blocking until a slot is available. len(src) must equal Ring.SlotSize.
func (*Ring) PushTimeout ¶
PushTimeout writes src into the ring, blocking up to timeout if the ring is full. It returns an error wrapping ErrTimeout if timeout elapses first.
func (*Ring) TryPop ¶
TryPop reads the next queued slot into dst without blocking. It reports false if the ring is empty. len(dst) must equal Ring.SlotSize.
type UnfairLock ¶
type UnfairLock struct {
// contains filtered or unexported fields
}
UnfairLock is a mutual exclusion lock backed by Darwin's os_unfair_lock. The zero value is an unlocked lock ready for use.
Because os_unfair_lock records the owning OS thread in the kernel for priority inheritance, UnfairLock.Lock and a successful UnfairLock.TryLock pin the calling goroutine to its OS thread with runtime.LockOSThread, and UnfairLock.Unlock releases that pin. Unlock must be called from the same goroutine that acquired the lock.
An UnfairLock must not be copied after first use.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/ossync"
)
func main() {
var mu ossync.UnfairLock
total := 0
mu.Lock()
total += 42
mu.Unlock()
fmt.Println("total:", total)
}
Output: total: 42
func (*UnfairLock) Lock ¶
func (l *UnfairLock) Lock()
Lock acquires the lock, blocking until it is available.
func (*UnfairLock) LockAdaptive ¶
func (l *UnfairLock) LockAdaptive()
LockAdaptive acquires the lock using OS_UNFAIR_LOCK_FLAG_ADAPTIVE_SPIN when supported (macOS 15+), falling back to UnfairLock.Lock on earlier systems.
func (*UnfairLock) TryLock ¶
func (l *UnfairLock) TryLock() bool
TryLock attempts to acquire the lock without blocking. It reports whether the lock was acquired.
func (*UnfairLock) Unlock ¶
func (l *UnfairLock) Unlock()
Unlock releases the lock. It must be called by the goroutine holding l.