Go Wiki:限制資源使用
要限制程式對記憶體等有限資源的使用,可以讓 goroutine 使用帶緩衝的通道同步對該資源的使用(即,使用通道作為訊號量)
const (
AvailableMemory = 10 << 20 // 10 MB
AverageMemoryPerRequest = 10 << 10 // 10 KB
MaxOutstanding = AvailableMemory / AverageMemoryPerRequest
)
var sem = make(chan int, MaxOutstanding)
func Serve(queue chan *Request) {
for {
sem <- 1 // Block until there's capacity to process a request.
req := <-queue
go handle(req) // Don't wait for handle to finish.
}
}
func handle(r *Request) {
process(r) // May take a long time & use a lot of memory or CPU
<-sem // Done; enable next request to run.
}
參考
Effective Go 關於通道的討論:https://golang.com.tw/doc/effective_go#channels
此內容是 Go Wiki 的一部分。