workergroup.go 509 B

123456789101112131415161718192021222324
  1. package threading
  2. // A WorkerGroup is used to run given number of workers to process jobs.
  3. type WorkerGroup struct {
  4. job func()
  5. workers int
  6. }
  7. // NewWorkerGroup returns a WorkerGroup with given job and workers.
  8. func NewWorkerGroup(job func(), workers int) WorkerGroup {
  9. return WorkerGroup{
  10. job: job,
  11. workers: workers,
  12. }
  13. }
  14. // Start starts a WorkerGroup.
  15. func (wg WorkerGroup) Start() {
  16. group := NewRoutineGroup()
  17. for i := 0; i < wg.workers; i++ {
  18. group.RunSafe(wg.job)
  19. }
  20. group.Wait()
  21. }