v2ray-core/common/signal/exec.go

47 lines
808 B
Go
Raw Normal View History

2016-12-29 21:17:12 +00:00
package signal
import (
"context"
)
2016-12-29 21:17:12 +00:00
func executeAndFulfill(f func() error, done chan<- error) {
err := f()
if err != nil {
done <- err
}
close(done)
}
2017-02-23 18:30:37 +00:00
// ExecuteAsync executes a function asychrously and return its result.
2016-12-29 21:17:12 +00:00
func ExecuteAsync(f func() error) <-chan error {
done := make(chan error, 1)
go executeAndFulfill(f, done)
return done
}
func ErrorOrFinish1(ctx context.Context, c <-chan error) error {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-c:
return err
}
}
func ErrorOrFinish2(ctx context.Context, c1, c2 <-chan error) error {
2016-12-29 21:17:12 +00:00
select {
case <-ctx.Done():
return ctx.Err()
2017-04-17 17:33:22 +00:00
case err := <-c1:
if err != nil {
2016-12-29 21:17:12 +00:00
return err
}
return ErrorOrFinish1(ctx, c2)
2017-04-17 17:33:22 +00:00
case err := <-c2:
if err != nil {
2016-12-29 21:17:12 +00:00
return err
}
return ErrorOrFinish1(ctx, c1)
2016-12-29 21:17:12 +00:00
}
}