猿问

是否有缓冲锁定模式?

在 Go 中有一个缓冲通道的概念。那是一个在你填满它的缓冲区之前不会被阻塞的通道。

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


翻阅古今
浏览 101回答 1
1回答

湖上湖

为有限数量的客户端锁定某些资源的原语称为信号量。它很容易通过缓冲通道实现:var semaphore = make(chan struct{}, 4) // allow four concurrent usersfunc f() {&nbsp; &nbsp; // Grab the lock. Blocks as long as 4 other invocations of f are still running.&nbsp; &nbsp; semaphore <- struct{}{}&nbsp; &nbsp; // Release the lock once we're done.&nbsp; &nbsp; defer func() { <-semaphore }()&nbsp; &nbsp; // Do work...}
随时随地看视频慕课网APP

相关分类

Go
我要回答