1. import (
  2. "fmt"
  3. "sync"
  4. "time"
  5. )
  6. type Task struct {
  7. Id int
  8. }
  9. type Pool struct {
  10. MaxWorkers int
  11. Tasks chan Task
  12. wg sync.WaitGroup
  13. }
  14. func NewPool(maxWorkers int) *Pool {
  15. return &Pool{
  16. MaxWorkers: maxWorkers,
  17. Tasks: make(chan Task),
  18. }
  19. }
  20. func (p *Pool) Start() {
  21. for i := 0; i < p.MaxWorkers; i++ {
  22. go p.worker()
  23. }
  24. }
  25. func (p *Pool) worker() {
  26. defer p.wg.Done()
  27. for task := range p.Tasks {
  28. time.Sleep(time.Duration(2) * time.Second)
  29. fmt.Printf("Worker processing task %d\n", task.Id)
  30. }
  31. }
  32. func (p *Pool) AddTask(task Task) {
  33. p.wg.Add(1)
  34. p.Tasks <- task
  35. }
  36. func (p *Pool) Wait() {
  37. close(p.Tasks)
  38. p.wg.Wait()
  39. }
  40. func main() {
  41. pool := NewPool(10)
  42. pool.Start()
  43. for i := 0; i < 100; i++ {
  44. pool.AddTask(Task{Id: i})
  45. }
  46. pool.Wait()
  47. }