-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecutor.go
52 lines (42 loc) · 991 Bytes
/
executor.go
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
45
46
47
48
49
50
51
52
package concurrent
import (
"context"
"github.com/pkg/errors"
)
type Result interface{}
type Job func() Result
type Executor interface {
Execute(ctx context.Context, job Job) (Result, error)
}
type executor struct {
waiter Waiter
}
func NewExecutor(n int) Executor {
return &executor{
waiter: NewWaiter(n),
}
}
func (executor *executor) Execute(ctx context.Context, job Job) (Result, error) {
err := executor.waiter.Acquire(ctx)
if err != nil {
return nil, errors.Wrap(err, "No worker is available")
}
ch := make(chan interface{})
go func() {
defer executor.waiter.Release()
defer close(ch)
ch <- job()
}()
select {
case res := <-ch:
return res, nil
case <-ctx.Done():
// Invoke a new goroutine which reads the channel. It will ensure
// that the writer goroutine can write on the channel without
// blocking, and that the waiter will be released properly.
go func() {
<-ch
}()
return nil, errors.Wrap(ctx.Err(), "job is cancelled")
}
}