Semaphore With Chan Buffer And Timeout

Cap concurrent work by filling a buffered channel and bound waiting with a timeout case, so slow slots never block callers forever.

GoResilience

Code

gosnippet
44 lines
package main

import (
	"fmt"
	"time"
)

type Limiter struct {
	slots chan struct{}
}

func NewLimiter(n int) *Limiter {
	return &Limiter{slots: make(chan struct{}, n)}
}

// Acquire 占一个槽位:等待超过 timeout 返回 false
func (l *Limiter) Acquire(timeout time.Duration) bool {
	select {
	case l.slots <- struct{}{}:
		return true
	case <-time.After(timeout):
		return false
	}
}

func (l *Limiter) Release() { <-l.slots }

func (l *Limiter) InUse() int { return len(l.slots) }

func main() {
	limiter := NewLimiter(2)

	// 占满两个槽位
	fmt.Println("acquire 1:", limiter.Acquire(50*time.Millisecond))
	fmt.Println("acquire 2:", limiter.Acquire(50*time.Millisecond))
	fmt.Println("in use:", limiter.InUse())

	// 第三个等待超时:限流拒绝而不是无限阻塞
	fmt.Println("acquire 3 (timeout):", limiter.Acquire(20*time.Millisecond))

	limiter.Release()
	fmt.Println("after release, acquire 3:", limiter.Acquire(20*time.Millisecond))
	fmt.Println("in use:", limiter.InUse())
}

The workings

Count the functions NewLimiter, Acquire, Release and InUse as the entire surface area of Semaphore With Chan Buffer And Timeout.

Points of care

  • Only built-ins are called, so there is no dependency chain to audit.

Using it

Signature: func NewLimiter(n int) *Limiter

The run emits 5 labeled sections — acquire 1:, acquire 2:, in use:, acquire 3 (timeout):, after release, acquire 3: — one per step.

Treat main as the orchestrator calling NewLimiter, Acquire, InUse and Release in a fixed order.

Key statements

func (l *Limiter) InUse() int { return len(l.slots) }
return &Limiter{slots: make(chan struct{}, n)}
func (l *Limiter) Release() { <-l.slots }

Interactive Tools for This Topic

FAQ

What does Semaphore With Chan Buffer And Timeout print when run?
Running the file directly is enough — expect labeled output lines such as `acquire 1:`, `acquire 2:`, `in use:`.