You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
nathany edited this page Dec 10, 2014
·
3 revisions
Bounding resource use
To bound a program's use of a limited resource - like memory - have goroutines synchronize their use of that resource using a buffered channel (i.e., use the channel as a semaphore):
const (
AvailableMemory=10<<20// 10 MBAverageMemoryPerRequest=10<<10// 10 KBMaxOutstanding=AvailableMemory/AverageMemoryPerRequest
)
varsem=make(chanint, MaxOutstanding)
funcServe(queuechan*Request) {
for {
sem<-1// Block until there's capacity to process a request.req:=<-queuegohandle(req) // Don't wait for handle to finish.
}
}
funchandle(r*Request) {
process(r) // May take a long time & use a lot of memory or CPU<-sem// Done; enable next request to run.
}