diff options
| author | chrislu <chris.lu@gmail.com> | 2022-09-25 13:50:02 -0700 |
|---|---|---|
| committer | chrislu <chris.lu@gmail.com> | 2022-09-25 13:50:02 -0700 |
| commit | 1484cb224f4e31851a0e45ed29c6f0d072f0856f (patch) | |
| tree | 9d136d089dfba2c58246ae0517d18e5af6634630 /weed/util/limited_async_pool.go | |
| parent | 600d2f92a44b8fb76653ef0547bce5a406e82eb8 (diff) | |
| parent | cc570a4477a791312355dfd325a49bd276522997 (diff) | |
| download | seaweedfs-1484cb224f4e31851a0e45ed29c6f0d072f0856f.tar.xz seaweedfs-1484cb224f4e31851a0e45ed29c6f0d072f0856f.zip | |
Merge branch 'master' into message_send
Diffstat (limited to 'weed/util/limited_async_pool.go')
| -rw-r--r-- | weed/util/limited_async_pool.go | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/weed/util/limited_async_pool.go b/weed/util/limited_async_pool.go new file mode 100644 index 000000000..c78de158b --- /dev/null +++ b/weed/util/limited_async_pool.go @@ -0,0 +1,44 @@ +package util + +// initial version comes from https://hackernoon.com/asyncawait-in-golang-an-introductory-guide-ol1e34sg + +import "context" + +type Future interface { + Await() interface{} +} + +type future struct { + await func(ctx context.Context) interface{} +} + +func (f future) Await() interface{} { + return f.await(context.Background()) +} + +type LimitedAsyncExecutor struct { + executor *LimitedConcurrentExecutor +} + +func NewLimitedAsyncExecutor(limit int) *LimitedAsyncExecutor { + return &LimitedAsyncExecutor{ + executor: NewLimitedConcurrentExecutor(limit), + } +} + +func (ae *LimitedAsyncExecutor) Execute(job func() interface{}) Future { + var result interface{} + c := make(chan struct{}) + ae.executor.Execute(func() { + defer close(c) + result = job() + }) + return future{await: func(ctx context.Context) interface{} { + select { + case <-ctx.Done(): + return ctx.Err() + case <-c: + return result + } + }} +} |
