syncx Limit
syncx.Limit
Section titled “syncx.Limit”The syncx package provides a concurrency-limiting primitive via the Limit type. It uses a buffered channel as a semaphore to cap the number of simultaneous in-flight requests.
Variables
Section titled “Variables”ErrLimitReturn
Section titled “ErrLimitReturn”var ErrLimitReturn = errors.New("discarding limited token, resource pool is full, someone returned multiple times")Returned when a caller tries to return more tokens than were borrowed — i.e., the resource pool is already full.
type Limit struct { pool chan lang.PlaceholderType}Limit wraps a buffered channel pool that controls the number of concurrent requests.
Functions
Section titled “Functions”NewLimit
Section titled “NewLimit”func NewLimit(n int) LimitCreates a Limit that allows at most n concurrent borrows.
Parameters
n(int): Maximum number of simultaneous borrows allowed.
Returns
Limit: A newLimitinstance.
Borrow
Section titled “Borrow”func (l Limit) Borrow()Blocks until a token is available, then acquires it.
Return
Section titled “Return”func (l Limit) Return() errorReturns a previously borrowed token. Returns ErrLimitReturn if the pool is already full (i.e., a token was returned more times than it was borrowed).
Returns
error:nilon success,ErrLimitReturnon over-return.
TryBorrow
Section titled “TryBorrow”func (l Limit) TryBorrow() boolAttempts to acquire a token without blocking.
Returns
bool:trueif a token was acquired,falseif none are available.
Example
Section titled “Example”package main
import ( "fmt"
"github.com/zeromicro/go-zero/core/syncx")
func main() { limit := syncx.NewLimit(3) // allow at most 3 concurrent operations
// Non-blocking try if limit.TryBorrow() { fmt.Println("acquired token") if err := limit.Return(); err != nil { fmt.Println("return error:", err) } }
// Blocking borrow limit.Borrow() defer limit.Return() fmt.Println("doing work under limit")}