在Go中,有一个缓冲通道的概念。在填充缓冲区之前,该通道不会被阻塞。
通用缓冲锁定是否有任何通用模式?它将为有限数量的客户端锁定一些资源。
为有限数量的客户端锁定某些资源的原语称为信号量。
使用缓冲通道很容易实现:
var semaphore = make(chan struct{}, 4) // allow four concurrent users
func f() {
// Grab the lock. Blocks as long as 4 other invocations of f are still running.
semaphore <- struct{}{}
// Release the lock once we're done.
defer func() { <-semaphore }()
// Do work...
}