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://go.dev.org.tw/doc/effective_go#channels


此內容是 Go Wiki 的一部分。