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の一部です。