2020-07-26 17:09:05 +08:00
|
|
|
package threading
|
|
|
|
|
2021-02-26 16:27:04 +08:00
|
|
|
// A WorkerGroup is used to run given number of workers to process jobs.
|
2020-07-26 17:09:05 +08:00
|
|
|
type WorkerGroup struct {
|
|
|
|
job func()
|
|
|
|
workers int
|
|
|
|
}
|
|
|
|
|
2021-02-26 16:27:04 +08:00
|
|
|
// NewWorkerGroup returns a WorkerGroup with given job and workers.
|
2020-07-26 17:09:05 +08:00
|
|
|
func NewWorkerGroup(job func(), workers int) WorkerGroup {
|
|
|
|
return WorkerGroup{
|
|
|
|
job: job,
|
|
|
|
workers: workers,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-26 16:27:04 +08:00
|
|
|
// Start starts a WorkerGroup.
|
2020-07-26 17:09:05 +08:00
|
|
|
func (wg WorkerGroup) Start() {
|
|
|
|
group := NewRoutineGroup()
|
|
|
|
for i := 0; i < wg.workers; i++ {
|
|
|
|
group.RunSafe(wg.job)
|
|
|
|
}
|
|
|
|
group.Wait()
|
|
|
|
}
|