Go Wiki:限制资源使用

要限制程序对有限资源(如内存)的使用,让协程使用缓冲通道同步对该资源的使用(即,使用通道作为信号量)

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.ac.cn/doc/effective_go#channels


此内容是 Go Wiki 的一部分。