1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-01-21 08:46:31 -05:00
v2fly/common/signal/exec.go

48 lines
898 B
Go
Raw Normal View History

2016-12-29 16:17:12 -05:00
package signal
import (
"context"
)
2018-04-11 10:15:29 -04:00
// Execute runs a list of tasks sequentially, returns the first error encountered or nil if all tasks pass.
func Execute(tasks ...func() error) error {
for _, task := range tasks {
if err := task(); err != nil {
return err
}
}
return nil
}
2018-04-11 10:45:09 -04:00
// ExecuteParallel executes a list of tasks asynchronously, returns the first error encountered or nil if all tasks pass.
func ExecuteParallel(ctx context.Context, tasks ...func() error) error {
n := len(tasks)
s := NewSemaphore(n)
2016-12-29 16:17:12 -05:00
done := make(chan error, 1)
2018-04-11 10:45:09 -04:00
for _, task := range tasks {
<-s.Wait()
go func(f func() error) {
if err := f(); err != nil {
select {
case done <- err:
default:
}
}
s.Signal()
}(task)
}
2018-04-11 10:45:09 -04:00
for i := 0; i < n; i++ {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-done:
2016-12-29 16:17:12 -05:00
return err
2018-04-11 10:45:09 -04:00
case <-s.Wait():
2016-12-29 16:17:12 -05:00
}
}
2018-04-11 10:45:09 -04:00
return nil
2016-12-29 16:17:12 -05:00
}