mirror of
https://github.com/XTLS/Xray-core.git
synced 2025-04-29 16:58:34 +00:00
v1.0.0
This commit is contained in:
parent
47d23e9972
commit
c7f7c08ead
711 changed files with 82154 additions and 2 deletions
52
common/task/task.go
Normal file
52
common/task/task.go
Normal file
|
@ -0,0 +1,52 @@
|
|||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common/signal/semaphore"
|
||||
)
|
||||
|
||||
// OnSuccess executes g() after f() returns nil.
|
||||
func OnSuccess(f func() error, g func() error) func() error {
|
||||
return func() error {
|
||||
if err := f(); err != nil {
|
||||
return err
|
||||
}
|
||||
return g()
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
n := len(tasks)
|
||||
s := semaphore.New(n)
|
||||
done := make(chan error, 1)
|
||||
|
||||
for _, task := range tasks {
|
||||
<-s.Wait()
|
||||
go func(f func() error) {
|
||||
err := f()
|
||||
if err == nil {
|
||||
s.Signal()
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case done <- err:
|
||||
default:
|
||||
}
|
||||
}(task)
|
||||
}
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-s.Wait():
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue