29 lines
674 B
Go
29 lines
674 B
Go
package channel
|
|
|
|
// LimitedRunner is a Runner which runs its methods
|
|
// in a pre-defined amount of routines
|
|
type LimitedRunner struct {
|
|
limiter chan struct{}
|
|
}
|
|
|
|
var _ Runner = &LimitedRunner{}
|
|
|
|
// NewLimitedRunner returns a new LimitedRunner with the given amount
|
|
// of allowed routines
|
|
func NewLimitedRunner(routineLimit int) *LimitedRunner {
|
|
return &LimitedRunner{
|
|
limiter: make(chan struct{}, routineLimit),
|
|
}
|
|
}
|
|
|
|
// Run blocks if the limit is currently exceeded.
|
|
// It blocks until a routine becomes available again.
|
|
// For non-blocking behavior, use go syntax
|
|
func (r *LimitedRunner) Run(f func()) {
|
|
r.limiter <- struct{}{}
|
|
go func() {
|
|
f()
|
|
<-r.limiter
|
|
}()
|
|
}
|