Skip to content

Commit 0aa4c68

Browse files
authored
Merge pull request #51 from appleboy/patch2
chore(executor): only wait number of go routine
2 parents 018fcd9 + 1ca59f1 commit 0aa4c68

1 file changed

Lines changed: 21 additions & 16 deletions

File tree

internal/executor/executor.go

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,36 +13,41 @@ func ExecuteAll(numCPU int, tasks ...TaskFunc) error {
1313
ctx, cancel := context.WithCancel(context.Background())
1414
defer cancel()
1515

16-
wg := sync.WaitGroup{}
17-
wg.Add(len(tasks))
18-
1916
if numCPU == 0 {
2017
numCPU = runtime.NumCPU()
2118
}
22-
queue := make(chan TaskFunc, numCPU)
19+
20+
wg := sync.WaitGroup{}
21+
wg.Add(numCPU)
22+
23+
queue := make(chan TaskFunc, len(tasks))
24+
// Add tasks to queue
25+
for _, task := range tasks {
26+
queue <- task
27+
}
28+
close(queue)
2329

2430
// Spawn the executer
2531
for i := 0; i < numCPU; i++ {
2632
go func() {
27-
for task := range queue {
28-
if err == nil {
29-
taskErr := task(ctx)
30-
if taskErr != nil {
31-
err = taskErr
33+
defer wg.Done()
34+
for {
35+
select {
36+
case task, ok := <-queue:
37+
if ctx.Err() != nil || !ok {
38+
return
39+
}
40+
if e := task(ctx); e != nil {
41+
err = e
3242
cancel()
3343
}
44+
case <-ctx.Done():
45+
return
3446
}
35-
wg.Done()
3647
}
3748
}()
3849
}
3950

40-
// Add tasks to queue
41-
for _, task := range tasks {
42-
queue <- task
43-
}
44-
close(queue)
45-
4651
// wait for all task done
4752
wg.Wait()
4853
return err

0 commit comments

Comments
 (0)