spin

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 4 Imported by: 4 modules, 3 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.

README

spin

Go Reference Benchmarks Codecov

Spin locks and adaptive waits for short-lived contention in Go.

English | 简体中文 | Español | 日本語 | Français

Overview

Lock protects shared state in very short critical sections. Wait lets a goroutine poll a condition it expects to change soon. Under contention, both pause briefly at first and yield to the Go scheduler more often as the wait continues.

Installation

Requires Go 1.27 or later.

go get code.hybscloud.com/spin

Usage

All writers share mu and both counters. Recording a 64-byte packet takes one short critical section.

var mu spin.Lock
var packets, bytes int

mu.Lock()
packets++
bytes += 64
mu.Unlock()

When local work should be ready soon, keep one Wait across retries. The caller supplies the workReady check.

var wait spin.Wait
for !workReady() {
	wait.Once()
}

Use Pause between checks in a short, bounded polling loop.

spin.Pause()

Use Yield when the next retry can wait for the configured sleep interval.

spin.Yield()

Lock and Wait

  • Lock is non-fair and its zero value is unlocked. Try() attempts to acquire it once and returns true on success. For general-purpose locking, use sync.Mutex.
  • Each polling goroutine uses its own zero-value Wait. WillYield() reports whether the next Once() will call runtime.Gosched() directly. Reset() restores the initial pause interval.

Pause and Yield

  • On targets with an assembly implementation, Pause(n) repeats a processor hint n times in a tight polling loop. An omitted or non-positive count selects 30 repetitions. The elapsed time depends on the processor.
  • Yield(d) sleeps for d if the duration is positive and calls runtime.Gosched() otherwise. Yield() uses the default duration, initially 250 µs. SetYieldDuration(d) changes that default.

Platform support

Pause uses assembly on 386, amd64, arm64, loong64, ppc64le, riscv64, and s390x. On other targets, including arm and wasm, each call to Pause yields once through runtime.Gosched().

License

MIT License

©2025 Hayabusa Cloud Co., Ltd.

Documentation

Overview

Package spin provides synchronization primitives for short local waits.

Lock is a non-fair lock for very short critical sections. Lock.Lock waits for ownership and Lock.Try makes a single acquisition attempt.

Wait pauses briefly and yields to the Go scheduler more often as contention persists. Pause issues processor hints on supported targets. Yield sleeps for a positive duration or yields to the scheduler for a non-positive duration.

Architectures: amd64, arm64, 386, arm, riscv64, ppc64le, s390x, loong64, wasm.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Pause

func Pause(cycles ...int)

Pause executes CPU pause instructions to reduce energy consumption in spin-wait loops. On hardware-pause targets, it does not block or yield the scheduler. On wasm and unsupported fallback targets, it may yield via runtime.Gosched.

Defaults to 30 pause hints if not specified. The cycles parameter is a historical repeat-count name, not a calibrated CPU-cycle delay. Uses optimized assembly on supported hardware-pause targets.

Usage:

Pause()     // 30 pause hints (default)
Pause(1)    // 1 pause hint
Pause(50)   // 50 pause hints

func SetYieldDuration

func SetYieldDuration(d time.Duration)

SetYieldDuration sets the base duration unit for Yield(). Safe for concurrent use. Recommended: 50-250 microseconds for real-time systems, 1-4 ms for general workloads.

func Yield

func Yield(duration ...time.Duration)

Yield cooperatively yields execution to reduce CPU burn in tight loops.

By default, Yield sleeps for a small duration (configured by SetYieldDuration) to give other goroutines and the OS scheduler a chance to run.

If an explicit duration is provided, it overrides the default for this call. A non-positive duration disables sleeping and falls back to runtime.Gosched() (a purely cooperative yield without a timer sleep).

For automatic adaptive backoff in tight loops, use Wait instead.

Example
package main

import (
	"fmt"
	"time"

	"code.hybscloud.com/spin"
)

func main() {
	spin.Yield(10 * time.Millisecond)
	fmt.Println("yielded")
}

Types

type Lock

type Lock struct {
	// contains filtered or unexported fields
}

Lock is a minimal, non-fair spin lock intended for very short critical sections on hot paths. It avoids allocations and OS mutex overhead but should not be used as a general-purpose lock.

Acquisition uses FAA (Fetch-And-Add) with a TTAS (test-and-test-and-set) slow path. FAA completes in a single atomic instruction (LOCK XADD on x86, LDADDAL on arm64) — under contention, CAS produces O(n²) cache-line invalidations while FAA keeps traffic at O(n). The TTAS slow path spins on read-only Load (MESI Shared) to avoid bouncing the cache line, and only attempts FAA when the lock appears free.

Example
package main

import (
	"fmt"

	"code.hybscloud.com/spin"
)

func main() {
	var lk spin.Lock
	lk.Lock()
	// critical section
	lk.Unlock()
	fmt.Println("locked")
}
Output:
locked

func (*Lock) Lock

func (sl *Lock) Lock()

Lock acquires the lock. Fast path: single FAA. Slow path: TTAS (test-and-test-and-set) — spin on read-only Load to keep the cache line in MESI Shared state, then attempt FAA only when the lock appears free.

func (*Lock) Try

func (sl *Lock) Try() bool

Try attempts to acquire the lock without blocking. It returns true if the lock was acquired.

Uses FAA rather than CAS: on x86 LOCK CMPXCHG takes exclusive cache-line ownership regardless of comparison outcome, so a failed CAS costs the same coherence traffic as FAA. FAA keeps the atomic pattern consistent across the Lock API.

A failed Try increments n without a corresponding decrement. This is intentional: Unlock resets n to zero via Store(0), clearing all accumulated increments. The uintptr counter space is large enough that overflow is not a practical concern.

func (*Lock) Unlock

func (sl *Lock) Unlock()

Unlock releases the lock.

type Wait

type Wait struct {
	// contains filtered or unexported fields
}

Wait adapts to short local contention. The zero value is ready to use.

Example
package main

import (
	"fmt"
	"sync/atomic"
	"time"

	"code.hybscloud.com/spin"
)

func main() {
	var sw spin.Wait
	var ready atomic.Bool
	go func() {
		time.Sleep(50 * time.Microsecond)
		ready.Store(true)
	}()
	for !ready.Load() {
		sw.Once()
	}
	fmt.Println("ready")
}
Output:
ready

func (*Wait) Once

func (s *Wait) Once()

Once takes one wait step. It starts with Pause and calls runtime.Gosched more often as the wait continues.

func (*Wait) Reset

func (s *Wait) Reset()

Reset starts the wait again at its initial pause interval.

func (*Wait) WillYield

func (s *Wait) WillYield() bool

WillYield reports whether the next Wait.Once calls runtime.Gosched directly. It leaves the wait state unchanged. On fallback targets, Pause can also yield to the scheduler.

Directories

Path Synopsis
internal
pause
Package pause contains arch-specific pause/yield primitives.
Package pause contains arch-specific pause/yield primitives.

Jump to

Keyboard shortcuts

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