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 time
for _, task := range tasks {
// blocks until a slot is free and acquires it
if err := cm.AcquireContext(ctx); err != nil {
// error means either the context is done or Wait has been called
return
}
go func(t Task) {
defer cm.Release() // releases slot
process(t)
}(task)
}
fmt.Printf("currently running %d goroutines\n", cm.RunningCount())
cm.Wait() // blocks until all slots are releasedno context? use cm.Acquire() instead
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.
MIT