1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 10:08:15 -05:00
This commit is contained in:
Darien Raymond 2018-06-04 14:29:05 +02:00
parent ee0ca6cbd2
commit 54e2244c5a
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169

View File

@ -10,29 +10,23 @@ type Task func() error
type executionContext struct { type executionContext struct {
ctx context.Context ctx context.Context
task Task tasks []Task
onSuccess Task onSuccess Task
onFailure Task onFailure Task
} }
func (c *executionContext) executeTask() error { func (c *executionContext) executeTask() error {
if c.ctx == nil && c.task == nil { if len(c.tasks) == 0 {
return nil return nil
} }
if c.ctx == nil { ctx := context.Background()
return c.task()
if c.ctx != nil {
ctx = c.ctx
} }
if c.task == nil { return executeParallel(ctx, c.tasks)
<-c.ctx.Done()
return c.ctx.Err()
}
return executeParallel(func() error {
<-c.ctx.Done()
return c.ctx.Err()
}, c.task)
} }
func (c *executionContext) run() error { func (c *executionContext) run() error {
@ -56,17 +50,15 @@ func WithContext(ctx context.Context) ExecutionOption {
func Parallel(tasks ...Task) ExecutionOption { func Parallel(tasks ...Task) ExecutionOption {
return func(c *executionContext) { return func(c *executionContext) {
c.task = func() error { c.tasks = append(c.tasks, tasks...)
return executeParallel(tasks...)
}
} }
} }
func Sequential(tasks ...Task) ExecutionOption { func Sequential(tasks ...Task) ExecutionOption {
return func(c *executionContext) { return func(c *executionContext) {
c.task = func() error { c.tasks = append(c.tasks, func() error {
return execute(tasks...) return execute(tasks...)
} })
} }
} }
@ -107,7 +99,7 @@ func execute(tasks ...Task) error {
} }
// executeParallel executes a list of tasks asynchronously, returns the first error encountered or nil if all tasks pass. // executeParallel executes a list of tasks asynchronously, returns the first error encountered or nil if all tasks pass.
func executeParallel(tasks ...Task) error { func executeParallel(ctx context.Context, tasks []Task) error {
n := len(tasks) n := len(tasks)
s := semaphore.New(n) s := semaphore.New(n)
done := make(chan error, 1) done := make(chan error, 1)
@ -129,6 +121,8 @@ func executeParallel(tasks ...Task) error {
select { select {
case err := <-done: case err := <-done:
return err return err
case <-ctx.Done():
return ctx.Err()
case <-s.Wait(): case <-s.Wait():
} }
} }