Home > Article > Backend Development > Can You Create a "Buffered Lock" in Go?
Go introduces the concept of buffered channels, allowing channels to accept messages without blocking until the buffer is filled. This raises the question: can a similar pattern be applied to locking mechanisms, creating a "buffered lock" that restricts resource access to a specific number of clients?
The primitive designed for managing access to shared resources while limiting client concurrency is known as a semaphore. In Go, semaphores can be easily implemented using buffered channels.
Consider the following code snippet:
var semaphore = make(chan struct{}, 4) // limit to 4 concurrent users func f() { // Acquire the lock. Blocks until at most 3 other goroutines are already executing f. semaphore <- struct{}{} // Release the lock when done. defer func() { <-semaphore }() // Perform the protected work... }
Here, the semaphore is represented by a buffered channel of size 4, which allows up to four concurrent invocations of the function f. The <-semaphore operation retrieves a value from the channel, blocking until one becomes available. The <-semaphore operation releases a value back into the channel, allowing another goroutine to acquire the lock.
Semaphores provide a simple and effective mechanism for implementing buffered locking in Go, enabling controlled access to shared resources by a limited number of clients.
The above is the detailed content of Can You Create a "Buffered Lock" in Go?. For more information, please follow other related articles on the PHP Chinese website!