Parallelize

kubernetes/client-go: util/workqueue/parallelizer.go

  1. type DoWorkPieceFunc func(piece int)
  2. // Parallelize is a very simple framework that allow for parallelizing
  3. // N independent pieces of work.
  4. func Parallelize(workers, pieces int, doWorkPiece DoWorkPieceFunc) {
  5. toProcess := make(chan int, pieces)
  6. for i := 0; i < pieces; i++ {
  7. toProcess <- i
  8. }
  9. close(toProcess)
  10. if pieces < workers {
  11. workers = pieces
  12. }
  13. wg := sync.WaitGroup{}
  14. wg.Add(workers)
  15. for i := 0; i < workers; i++ {
  16. go func() {
  17. defer utilruntime.HandleCrash()
  18. defer wg.Done()
  19. for piece := range toProcess {
  20. doWorkPiece(piece)
  21. }
  22. }()
  23. }
  24. wg.Wait()
  25. }