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