Source File
semaphore.go
Belonging Package
github.com/redis/go-redis/v9/internal
package internalimport ()var semTimers = sync.Pool{New: func() interface{} {:= time.NewTimer(time.Hour).Stop()return},}// putSemTimer stops a pooled timer and drains a stale fire before reuse,// portably across both timer-channel semantics (the drain must never block)://// - main module on go >= 1.23 (synchronous channels): Stop returns TRUE for// an expired-but-undelivered fire — the delivery is aborted — and false// only once the value was actually received. With the sole receiver// being Acquire's own select, the drain branch is unreachable; the// select-with-default is a safety net so a future semantics shift cannot// turn it into a blocking receive (reviewed on #3942).// - GODEBUG=asynctimerchan=1 (consumer main module on go < 1.23, old// buffered channels): Stop returns false and the fired value sits in the// buffer; the drain consumes it so the timer is clean for Reset-reuse.func putSemTimer( *time.Timer) {if !.Stop() {select {case <-.C:default:}}semTimers.Put()}// FastSemaphore is a channel-based semaphore optimized for performance.// It uses a fast path that avoids timer allocation when tokens are available.// The channel is pre-filled with tokens: Acquire = receive, Release = send.// Closing the semaphore unblocks all waiting goroutines.//// Performance: ~30 ns/op with zero allocations on fast path.// Fairness: Eventual fairness (no starvation) but not strict FIFO.type FastSemaphore struct {tokens chan struct{}max int32}// NewFastSemaphore creates a new fast semaphore with the given capacity.func ( int32) *FastSemaphore {:= make(chan struct{}, )// Pre-fill with tokensfor := int32(0); < ; ++ {<- struct{}{}}return &FastSemaphore{tokens: ,max: ,}}// Available returns the number of tokens currently free (an approximation under// concurrency). Zero means every turn is taken — by an in-use connection or an// in-flight dial — so the next Acquire would block. Used as a non-blocking// capacity probe; not a synchronization primitive.func ( *FastSemaphore) () int {return len(.tokens)}// TryAcquire attempts to acquire a token without blocking.// Returns true if successful, false if no tokens available.func ( *FastSemaphore) () bool {select {case <-.tokens:return truedefault:return false}}// Acquire acquires a token, blocking if necessary until one is available.// Returns an error if the context is cancelled or the timeout expires.// Uses a fast path to avoid timer allocation when tokens are immediately available.func ( *FastSemaphore) ( context.Context, time.Duration, error) error {// Check context firstselect {case <-.Done():return .Err()default:}// Try fast path first (no timer needed)select {case <-.tokens:return nildefault:}// Slow path: need to wait with timeout:= semTimers.Get().(*time.Timer)defer putSemTimer().Reset()select {case <-.tokens:return nilcase <-.Done():return .Err()case <-.C:return}}// AcquireBlocking acquires a token, blocking indefinitely until one is available.func ( *FastSemaphore) () {<-.tokens}// Release releases a token back to the semaphore.func ( *FastSemaphore) () {.tokens <- struct{}{}}// Close closes the semaphore, unblocking all waiting goroutines.// After close, all Acquire calls will receive a closed channel signal.func ( *FastSemaphore) () {close(.tokens)}// Len returns the current number of acquired tokens.func ( *FastSemaphore) () int32 {return .max - int32(len(.tokens))}// FIFOSemaphore is a channel-based semaphore with strict FIFO ordering.// Unlike FastSemaphore, this guarantees that threads are served in the exact order they call Acquire().// The channel is pre-filled with tokens: Acquire = receive, Release = send.// Closing the semaphore unblocks all waiting goroutines.//// Performance: ~115 ns/op with zero allocations (slower than FastSemaphore due to timer allocation).// Fairness: Strict FIFO ordering guaranteed by Go runtime.type FIFOSemaphore struct {tokens chan struct{}max int32}// NewFIFOSemaphore creates a new FIFO semaphore with the given capacity.func ( int32) *FIFOSemaphore {:= make(chan struct{}, )// Pre-fill with tokensfor := int32(0); < ; ++ {<- struct{}{}}return &FIFOSemaphore{tokens: ,max: ,}}// TryAcquire attempts to acquire a token without blocking.// Returns true if successful, false if no tokens available.func ( *FIFOSemaphore) () bool {select {case <-.tokens:return truedefault:return false}}// Acquire acquires a token, blocking if necessary until one is available.// Returns an error if the context is cancelled or the timeout expires.// Always uses timer to guarantee FIFO ordering (no fast path).func ( *FIFOSemaphore) ( context.Context, time.Duration, error) error {// No fast path - always use timer to guarantee FIFO:= semTimers.Get().(*time.Timer)defer putSemTimer().Reset()select {case <-.tokens:return nilcase <-.Done():return .Err()case <-.C:return}}// Release releases a token back to the semaphore.func ( *FIFOSemaphore) () {.tokens <- struct{}{}}
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |