2022-02-09 12:10:02 +01:00
|
|
|
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() {
|
2022-03-30 15:23:47 +02:00
|
|
|
defer func() { <-r.limiter }()
|
2022-02-09 12:10:02 +01:00
|
|
|
f()
|
|
|
|
}()
|
|
|
|
}
|