Is there buffered lock pattern?

自古美人都是妖i 提交于 2020-05-09 17:34:28

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/60004967/is-there-buffered-lock-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!