diff options
| author | hilimd <68371223+hilimd@users.noreply.github.com> | 2020-10-21 20:04:11 +0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-10-21 20:04:11 +0800 |
| commit | ab1105c52472946efab9713bf15df45e14ff4514 (patch) | |
| tree | 7af939a22f3efbf055054670ec8d2e3f11a79ad6 /weed/util/limiter.go | |
| parent | 2c40f56e5a2e4792361b6df0bb6e879726f340ab (diff) | |
| parent | 81cf8d04dfcbb84093044de4f10a8a92d9c8bd1c (diff) | |
| download | seaweedfs-ab1105c52472946efab9713bf15df45e14ff4514.tar.xz seaweedfs-ab1105c52472946efab9713bf15df45e14ff4514.zip | |
Merge pull request #31 from chrislusf/master
sync
Diffstat (limited to 'weed/util/limiter.go')
| -rw-r--r-- | weed/util/limiter.go | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/weed/util/limiter.go b/weed/util/limiter.go new file mode 100644 index 000000000..91499632c --- /dev/null +++ b/weed/util/limiter.go @@ -0,0 +1,40 @@ +package util + +// initial version comes from https://github.com/korovkin/limiter/blob/master/limiter.go + +// LimitedConcurrentExecutor object +type LimitedConcurrentExecutor struct { + limit int + tokenChan chan int +} + +func NewLimitedConcurrentExecutor(limit int) *LimitedConcurrentExecutor { + + // allocate a limiter instance + c := &LimitedConcurrentExecutor{ + limit: limit, + tokenChan: make(chan int, limit), + } + + // allocate the tokenChan: + for i := 0; i < c.limit; i++ { + c.tokenChan <- i + } + + return c +} + +// Execute adds a function to the execution queue. +// if num of go routines allocated by this instance is < limit +// launch a new go routine to execute job +// else wait until a go routine becomes available +func (c *LimitedConcurrentExecutor) Execute(job func()) { + token := <-c.tokenChan + go func() { + defer func() { + c.tokenChan <- token + }() + // run the job + job() + }() +} |
