aboutsummaryrefslogtreecommitdiff
path: root/weed/util/limiter.go
diff options
context:
space:
mode:
authorChris Lu <chris.lu@gmail.com>2020-10-21 02:16:21 -0700
committerChris Lu <chris.lu@gmail.com>2020-10-21 02:16:21 -0700
commit3bf0116de1525517c82854de15d8dc3a0b59817b (patch)
treea78d58777f8dcfdb88f15c1567fe70b84cc09afa /weed/util/limiter.go
parentc31b2542489ea4cddffbf1efedbdb867fb6cdb2f (diff)
downloadseaweedfs-3bf0116de1525517c82854de15d8dc3a0b59817b.tar.xz
seaweedfs-3bf0116de1525517c82854de15d8dc3a0b59817b.zip
mount: less channel waiting
Diffstat (limited to 'weed/util/limiter.go')
-rw-r--r--weed/util/limiter.go40
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()
+ }()
+}