aboutsummaryrefslogtreecommitdiff
path: root/weed/util/limited_async_pool.go
blob: c78de158b9f3356129b5f3b2cacfae60522fd9f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
		}
	}}
}