a more robust implementation is almost done in the
mutex-cond-implbranch.
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)
}
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.- calling
Waitagain from the same goroutine is a safe no-op, however calling it concurrently from multiple goroutines may panic.
MIT