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://go.dokyumento.jp/doc/effective_go#channels


このコンテンツはGo Wikiの一部です。