信号量是并发编程中比较常见的一种同步机制,它会保持资源计数器一直在0-N
(N
表示权重值大小,在用户初始化时指定)之间。当用户获取的时候会减少一会,使用完毕后再恢复过来。当遇到请求时资源不够的情况下,将会进入休眠状态以等待其它进程释放资源。
在 Golang 官方扩展库中为我们提供了一个基于权重的信号量 semaphore
并发原语。
你可以将下面的参数 n
理解为资源权重总和,表示每次获取时的权重;也可以理解为资源数量,表示每次获取时必须一次性获取的资源数量。为了理解方便,这里直接将其理解为资源数量。
数据结构
type waiter struct { n int64 ready chan<- struct{} // Closed when semaphore acquired. } // NewWeighted creates a new weighted semaphore with the given // maximum combined weight for concurrent access. func NewWeighted(n int64) *Weighted { w := &Weighted{size: n} return w } // Weighted provides a way to bound concurrent access to a resource. // The callers can request access with a given weight. type Weighted struct { size int64 cur int64 mu sync.Mutex waiters list.List }
一个 watier
就表示一个请求,其中n表示这次请求的资源数量(权重)。
使用 NewWeighted()
函数创建一个并发访问的最大资源数,这里 n
表示资源个数。