import (
"fmt"
"sync"
"time"
)
type Task struct {
Id int
}
type Pool struct {
MaxWorkers int
Tasks chan Task
wg sync.WaitGroup
}
func NewPool(maxWorkers int) *Pool {
return &Pool{
MaxWorkers: maxWorkers,
Tasks: make(chan Task),
}
}
func (p *Pool) Start() {
for i := 0; i < p.MaxWorkers; i++ {
go p.worker()
}
}
func (p *Pool) worker() {
defer p.wg.Done()
for task := range p.Tasks {
time.Sleep(time.Duration(2) * time.Second)
fmt.Printf("Worker processing task %d\n", task.Id)
}
}
func (p *Pool) AddTask(task Task) {
p.wg.Add(1)
p.Tasks <- task
}
func (p *Pool) Wait() {
close(p.Tasks)
p.wg.Wait()
}
func main() {
pool := NewPool(10)
pool.Start()
for i := 0; i < 100; i++ {
pool.AddTask(Task{Id: i})
}
pool.Wait()
}
本文档使用 521Wiki 发布