Created
August 21, 2023 16:43
-
-
Save daholino/ed3290aa40834979e9d6bc065bdbc76b to your computer and use it in GitHub Desktop.
Limit concurrent function executions using Go channels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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