1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-08 11:17:44 -05:00
v2fly/common/task/task.go

53 lines
874 B
Go
Raw Normal View History

2018-05-27 07:02:29 -04:00
package task
import (
"context"
2018-05-27 08:42:53 -04:00
"v2ray.com/core/common/signal/semaphore"
2018-05-27 07:02:29 -04:00
)
2018-12-06 05:35:02 -05:00
// OnSuccess executes g() after f() returns nil.
func OnSuccess(f func() error, g func() error) func() error {
2018-05-27 07:02:29 -04:00
return func() error {
2018-12-06 05:35:02 -05:00
if err := f(); err != nil {
2018-05-27 07:02:29 -04:00
return err
}
2018-12-06 05:35:02 -05:00
return g()
2018-05-27 07:02:29 -04:00
}
}
2018-12-06 05:35:02 -05:00
// Run executes a list of tasks in parallel, returns the first error encountered or nil if all tasks pass.
func Run(ctx context.Context, tasks ...func() error) error {
2018-05-27 07:02:29 -04:00
n := len(tasks)
2018-05-27 08:42:53 -04:00
s := semaphore.New(n)
2018-05-27 07:02:29 -04:00
done := make(chan error, 1)
for _, task := range tasks {
<-s.Wait()
2018-12-06 05:35:02 -05:00
go func(f func() error) {
2018-08-05 11:56:49 -04:00
err := f()
if err == nil {
s.Signal()
return
}
select {
case done <- err:
default:
2018-05-27 07:02:29 -04:00
}
}(task)
}
for i := 0; i < n; i++ {
select {
case err := <-done:
return err
2018-06-04 08:29:05 -04:00
case <-ctx.Done():
return ctx.Err()
2018-05-27 07:02:29 -04:00
case <-s.Wait():
}
}
return nil
}