有缓冲锁定模式吗?

时间:2020-01-31 13:35:10

标签: go design-patterns

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

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

1 个答案:

答案 0 :(得分:7)

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

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

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...
}
相关问题