本文介绍了有缓冲锁定模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Go there is a concept of buffered channel. That is a channel that will not be blocked until you fill its buffer.

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

Is there any general pattern for general buffered locking? It will lock some resource for limited amount of clients.

推荐答案

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

The primitive that locks some resource for a limited amount of clients is called a semaphore.

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

It's easily implemented with a buffered channel:

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

这篇关于有缓冲锁定模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:58