-
Notifications
You must be signed in to change notification settings - Fork 269
/
async_pool_impl.go
179 lines (144 loc) · 3.75 KB
/
async_pool_impl.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package workerpool
import (
"context"
"sync"
"sync/atomic"
"github.com/pingcap/errors"
cerrors "github.com/pingcap/tiflow/pkg/errors"
"github.com/pingcap/tiflow/pkg/retry"
"golang.org/x/sync/errgroup"
)
const (
backoffBaseDelayInMs = 1
maxTries = 25
)
type defaultAsyncPoolImpl struct {
workers []*asyncWorker
nextWorkerID int32
isRunning int32
runningLock sync.RWMutex
}
// NewDefaultAsyncPool creates a new AsyncPool that uses the default implementation
func NewDefaultAsyncPool(numWorkers int) AsyncPool {
return newDefaultAsyncPoolImpl(numWorkers)
}
func newDefaultAsyncPoolImpl(numWorkers int) *defaultAsyncPoolImpl {
workers := make([]*asyncWorker, numWorkers)
return &defaultAsyncPoolImpl{
workers: workers,
}
}
func (p *defaultAsyncPoolImpl) Go(ctx context.Context, f func()) error {
if p.doGo(ctx, f) == nil {
return nil
}
err := retry.Do(ctx, func() error {
return errors.Trace(p.doGo(ctx, f))
}, retry.WithBackoffBaseDelay(backoffBaseDelayInMs), retry.WithMaxTries(maxTries), retry.WithIsRetryableErr(isRetryable))
return errors.Trace(err)
}
func isRetryable(err error) bool {
return cerrors.IsRetryableError(err) && cerrors.ErrAsyncPoolExited.Equal(err)
}
func (p *defaultAsyncPoolImpl) doGo(ctx context.Context, f func()) error {
p.runningLock.RLock()
defer p.runningLock.RUnlock()
if atomic.LoadInt32(&p.isRunning) == 0 {
return cerrors.ErrAsyncPoolExited.GenWithStackByArgs()
}
task := &asyncTask{f: f}
worker := p.workers[int(atomic.AddInt32(&p.nextWorkerID, 1))%len(p.workers)]
worker.chLock.RLock()
defer worker.chLock.RUnlock()
if atomic.LoadInt32(&worker.isClosed) == 1 {
return cerrors.ErrAsyncPoolExited.GenWithStackByArgs()
}
select {
case <-ctx.Done():
return errors.Trace(ctx.Err())
case worker.inputCh <- task:
}
return nil
}
func (p *defaultAsyncPoolImpl) Run(ctx context.Context) error {
p.prepare()
errg := errgroup.Group{}
p.runningLock.Lock()
atomic.StoreInt32(&p.isRunning, 1)
p.runningLock.Unlock()
defer func() {
p.runningLock.Lock()
atomic.StoreInt32(&p.isRunning, 0)
p.runningLock.Unlock()
}()
errCh := make(chan error, len(p.workers))
defer close(errCh)
for _, worker := range p.workers {
workerFinal := worker
errg.Go(func() error {
err := workerFinal.run()
if err != nil && cerrors.ErrAsyncPoolExited.NotEqual(errors.Cause(err)) {
errCh <- err
}
return nil
})
}
errg.Go(func() error {
var err error
select {
case <-ctx.Done():
err = ctx.Err()
case err = <-errCh:
}
for _, worker := range p.workers {
worker.close()
}
return err
})
return errors.Trace(errg.Wait())
}
func (p *defaultAsyncPoolImpl) prepare() {
for i := range p.workers {
p.workers[i] = newAsyncWorker()
}
}
type asyncTask struct {
f func()
}
type asyncWorker struct {
inputCh chan *asyncTask
isClosed int32
chLock sync.RWMutex
}
func newAsyncWorker() *asyncWorker {
return &asyncWorker{inputCh: make(chan *asyncTask, 12800)}
}
func (w *asyncWorker) run() error {
for {
task := <-w.inputCh
if task == nil {
return cerrors.ErrAsyncPoolExited.GenWithStackByArgs()
}
task.f()
}
}
func (w *asyncWorker) close() {
if atomic.SwapInt32(&w.isClosed, 1) == 1 {
return
}
w.chLock.Lock()
defer w.chLock.Unlock()
close(w.inputCh)
}