a tiny concurrency manager for go
coma makes sure your program doesn't get overwhelmed with goroutines and fall into a coma.
- limits how many goroutines run at once
- waits until all of them are done
- is simple
- works
go get github.com/zlatej/comacm:=coma.New(5) // at most 5 goroutines at a timefor_, task:=rangetasks {
// blocks until a slot is free and acquires itiferr:=cm.AcquireContext(ctx); err!=nil {
// error means either the context is done or Wait has been calledreturn
}
gofunc() {
defercm.Release() // releases slotprocess(task)
}()
}
fmt.Printf("currently running %d goroutines\n", cm.RunningCount())
cm.Wait() // blocks until all slots are releasedno context? use cm.Acquire() instead
Newtreats amaxof less than 1 as 1.Waitis terminal: once called, the manager cannot be reused,Acquire/AcquireContextwill returnErrClosed.Waitcan safely be called any number of times, including concurrently from multiple goroutines.- every successful
Acquire/AcquireContextmust be matched by exactly oneRelease. An unmatchedReleasepanics when no slot is held.