-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalloter.go
46 lines (37 loc) · 882 Bytes
/
alloter.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
package alloter
import (
"context"
"sync"
)
type Alloter struct {}
func NewAlloter() *Alloter {
return &Alloter{}
}
func (c *Alloter) Exec(tasks *[]Task) error {
return c.execTasks(context.Background(), tasks)
}
func (c *Alloter) ExecWithContext(ctx context.Context, tasks *[]Task) error {
return c.execTasks(ctx, tasks)
}
func (c *Alloter) execTasks(ctx context.Context, tasks *[]Task) error {
size := len(*tasks)
if size == 0 {
return nil
}
errChan := make(chan error, size)
wg := sync.WaitGroup{}
wg.Add(size)
for _, task := range *tasks {
f := wrapperSimpleTask(task, &wg, &errChan)
go f()
}
// When error, wo can't close resChan, maybe some goroutines just finished.
// So, when error, wo just can wait auto GC.
child, cancel := context.WithCancel(ctx)
go func() {
wg.Wait()
cancel()
close(errChan)
}()
return blockGo(child, &errChan)
}