Skip to content

Commit

Permalink
update parallel
Browse files Browse the repository at this point in the history
  • Loading branch information
hucansen committed Aug 29, 2023
1 parent b9d5dea commit 4660998
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
26 changes: 14 additions & 12 deletions parallel/parallel.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,20 +35,24 @@ func Run[T any](ctx context.Context, limit uint, runners []Runner[T]) <-chan *Re
ctx = context.Background()
}

//go func() {
// select {
// case <-ctx.Done():
// err.Store(ctx.Err())
// case <-done:
// return
// }
//}()

go run[T](ctx, limit, runners, results)

return results
}
func run[T any](ctx context.Context, limit uint, runners []Runner[T], results chan *Result[T]) {
err := atomic.NewError(nil)
wg := sync.WaitGroup{}
sem := make(chan struct{}, limit)
done := make(chan struct{})

go func() {
select {
case <-ctx.Done():
err.Store(ctx.Err())
case <-done:
return
}
}()

for _, v := range runners {
sem <- struct{}{}
if err.Load() != nil {
Expand Down Expand Up @@ -85,8 +89,6 @@ func Run[T any](ctx context.Context, limit uint, runners []Runner[T]) <-chan *Re
close(results)
close(sem)
}()

return results
}

func Wait[T any](results <-chan *Result[T], handler func(v T) error) error {
Expand Down
4 changes: 3 additions & 1 deletion parallel/parallel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,17 @@ func TestRun1(t *testing.T) {
v := i
runners = append(runners, func(ctx context.Context) (result int, err error) {
result = v
time.Sleep(time.Duration(v) * time.Second)
return
})
}

values := parallel.Run[int](context.Background(), 2, runners)

t.Log("begin")
n := 0
err := parallel.Wait[int](values, func(v int) error {
n += v
t.Log(v)
return nil
})
require.NoError(t, err)
Expand Down

0 comments on commit 4660998

Please sign in to comment.