-
Notifications
You must be signed in to change notification settings - Fork 42
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
intro goroutine pool to restrain max concurrency
- Loading branch information
1 parent
21bc787
commit 113786d
Showing
5 changed files
with
93 additions
and
65 deletions.
There are no files selected for viewing
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package utils | ||
|
||
import ( | ||
"context" | ||
|
||
"golang.org/x/sync/semaphore" | ||
) | ||
|
||
type GoroutinePool struct { | ||
max int64 | ||
sem *semaphore.Weighted | ||
} | ||
|
||
func NewGoroutinePool(max int) *GoroutinePool { | ||
return &GoroutinePool{ | ||
max: int64(max), | ||
sem: semaphore.NewWeighted(int64(max)), | ||
} | ||
} | ||
|
||
func (p *GoroutinePool) Go(f func()) { | ||
p.sem.Acquire(context.Background(), 1) | ||
go func() { | ||
defer p.sem.Release(1) | ||
f() | ||
}() | ||
} | ||
|
||
func (p *GoroutinePool) Wait() { | ||
p.sem.Acquire(context.Background(), p.max) | ||
} |