Warm tip: This article is reproduced from stackoverflow.com, please click
design-patterns go

Is there buffered lock pattern?

发布于 2020-04-04 10:11:41

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.

Questioner
zored
Viewed
62
Peter 2020-01-31 21:58

The primitive that locks some resource for 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...
}