ossync

package
v0.6.20 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Rendered for darwin/amd64

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

Examples

Constants

View Source
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

View Source
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

func RingSize(capacity, slotSize int) int

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

func WaitTimeout[T Word](addr *T, expected T, timeout time.Duration, flags Flags) error

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

func WaitUint32(addr *uint32, expected uint32, flags Flags) error

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

func WaitUint64(addr *uint64, expected uint64, flags Flags) error

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.

func WakeAll

func WakeAll[T Word](addr *T, flags Flags) error

WakeAll wakes all waiters blocked on addr. If no waiters are currently blocked on addr (ENOENT), WakeAll returns nil.

func WakeOne

func WakeOne[T Word](addr *T, flags Flags) error

WakeOne wakes at most one waiter blocked on addr. If no waiter is currently blocked on addr (ENOENT), WakeOne returns nil.

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)

	// Shared enables cross-process wait/wake on an address inside a shared
	// 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

func InitRing(buf []byte, capacity, slotSize int, flags Flags) (*Ring, error)

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

func OpenRing(buf []byte) (*Ring, error)

OpenRing attaches to an existing Ring previously initialized in buf by InitRing (potentially in another process sharing the same mmap).

func (*Ring) Capacity

func (r *Ring) Capacity() int

Capacity returns the number of slots in the ring.

func (*Ring) Flags

func (r *Ring) Flags() Flags

Flags returns the synchronization flags (Local or Shared) of the ring.

func (*Ring) Len

func (r *Ring) Len() int

Len returns the approximate number of items currently queued in the ring.

func (*Ring) Pop

func (r *Ring) Pop(dst []byte) error

Pop reads the next queued slot into dst, blocking until an item is available. len(dst) must equal Ring.SlotSize.

func (*Ring) PopTimeout

func (r *Ring) PopTimeout(dst []byte, timeout time.Duration) error

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

func (r *Ring) Push(src []byte) error

Push writes src into the ring, blocking until a slot is available. len(src) must equal Ring.SlotSize.

func (*Ring) PushTimeout

func (r *Ring) PushTimeout(src []byte, timeout time.Duration) error

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) SlotSize

func (r *Ring) SlotSize() int

SlotSize returns the byte size of each slot.

func (*Ring) TryPop

func (r *Ring) TryPop(dst []byte) (bool, error)

TryPop reads the next queued slot into dst without blocking. It reports false if the ring is empty. len(dst) must equal Ring.SlotSize.

func (*Ring) TryPush

func (r *Ring) TryPush(src []byte) (bool, error)

TryPush writes src into the next available slot without blocking. It reports false if the ring is full. len(src) 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.

type Word

type Word interface {
	~uint32 | ~uint64
}

Word is an integer type supported by Darwin's wait-on-address APIs (32-bit or 64-bit).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL