在 Go 中有一個(gè)緩沖通道的概念。那是一個(gè)在你填滿它的緩沖區(qū)之前不會(huì)被阻塞的通道。通用緩沖鎖定是否有任何通用模式?它將為有限數(shù)量的客戶鎖定一些資源。
1 回答
湖上湖
TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
為有限數(shù)量的客戶端鎖定某些資源的原語(yǔ)稱為信號(hào)量。
它很容易通過(guò)緩沖通道實(shí)現(xiàn):
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...
}
- 1 回答
- 0 關(guān)注
- 119 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
