温馨提示:本文翻译自stackoverflow.com,查看原文请点击:go - Is there buffered lock pattern?
design-patterns go

go - 有缓冲锁定模式吗?

发布于 2020-04-04 10:33:37

在Go中,有一个缓冲通道的概念在填充缓冲区之前,该通道不会被阻塞。

通用缓冲锁定是否有任何通用模式它将为有限数量的客户端锁定一些资源。

查看更多

提问者
zored
被浏览
100
Peter 2020-01-31 21:58

为有限数量的客户端锁定某些资源的原语称为信号量

使用缓冲通道很容易实现:

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...
}