parallelizer.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package workqueue
  15. import (
  16. "sync"
  17. utilruntime "yunion.io/x/pkg/util/runtime"
  18. )
  19. type DoWorkPieceFunc func(piece int)
  20. // Parallelize is a very simple framework that allow for parallelizing
  21. // N independent pieces of work.
  22. func Parallelize(workers, pieces int, doWorkPiece DoWorkPieceFunc) {
  23. toProcess := make(chan int, pieces)
  24. for i := 0; i < pieces; i++ {
  25. toProcess <- i
  26. }
  27. close(toProcess)
  28. if pieces < workers {
  29. workers = pieces
  30. }
  31. wg := sync.WaitGroup{}
  32. wg.Add(workers)
  33. for i := 0; i < workers; i++ {
  34. go func() {
  35. defer utilruntime.HandleCrash()
  36. defer wg.Done()
  37. for piece := range toProcess {
  38. doWorkPiece(piece)
  39. }
  40. }()
  41. }
  42. wg.Wait()
  43. }