Skip to content

Instantly share code, notes, and snippets.

@daholino
Created August 21, 2023 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daholino/ed3290aa40834979e9d6bc065bdbc76b to your computer and use it in GitHub Desktop.
Save daholino/ed3290aa40834979e9d6bc065bdbc76b to your computer and use it in GitHub Desktop.
Limit concurrent function executions using Go channels
package limiter
import (
"errors"
"time"
)
type Limiter struct {
timeout time.Duration
ch chan struct{}
}
func NewLimiter(limit int, timeout time.Duration) *Limiter {
return &Limiter{
timeout: timeout,
ch: make(chan struct{}, limit),
}
}
func (l *Limiter) Execute(f func()) error {
select {
case l.ch <- struct{}{}:
// Added execution for running...
case <-time.After(l.timeout):
return errors.New("execution timed out")
}
// On exit, remove this execution from limit channel
defer func() {
<-l.ch
}()
f()
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment