1/*
2Copyright 2016 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package workqueue
18
19import (
20	"context"
21	"sync"
22
23	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
24)
25
26type DoWorkPieceFunc func(piece int)
27
28// ParallelizeUntil is a framework that allows for parallelizing N
29// independent pieces of work until done or the context is canceled.
30func ParallelizeUntil(ctx context.Context, workers, pieces int, doWorkPiece DoWorkPieceFunc) {
31	var stop <-chan struct{}
32	if ctx != nil {
33		stop = ctx.Done()
34	}
35
36	toProcess := make(chan int, pieces)
37	for i := 0; i < pieces; i++ {
38		toProcess <- i
39	}
40	close(toProcess)
41
42	if pieces < workers {
43		workers = pieces
44	}
45
46	wg := sync.WaitGroup{}
47	wg.Add(workers)
48	for i := 0; i < workers; i++ {
49		go func() {
50			defer utilruntime.HandleCrash()
51			defer wg.Done()
52			for piece := range toProcess {
53				select {
54				case <-stop:
55					return
56				default:
57					doWorkPiece(piece)
58				}
59			}
60		}()
61	}
62	wg.Wait()
63}
64