pool.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package worker // import "miniflux.app/v2/internal/worker"
  4. import (
  5. "sync"
  6. "miniflux.app/v2/internal/model"
  7. "miniflux.app/v2/internal/storage"
  8. )
  9. // Pool manages a set of background workers that process feed refresh jobs.
  10. type Pool struct {
  11. queue chan model.Job
  12. shutdown chan struct{}
  13. shutdownOnce sync.Once
  14. wg sync.WaitGroup
  15. }
  16. // Push sends a list of jobs to the queue.
  17. // Jobs pushed after Shutdown are discarded.
  18. func (p *Pool) Push(jobs model.JobList) {
  19. for _, job := range jobs {
  20. select {
  21. case p.queue <- job:
  22. case <-p.shutdown:
  23. return
  24. }
  25. }
  26. }
  27. // Shutdown stops accepting new jobs and waits for all workers to finish their current jobs.
  28. func (p *Pool) Shutdown() {
  29. p.shutdownOnce.Do(func() {
  30. close(p.shutdown)
  31. })
  32. p.wg.Wait()
  33. }
  34. // NewPool creates a pool of background workers.
  35. func NewPool(store *storage.Storage, nbWorkers int) *Pool {
  36. workerPool := &Pool{
  37. queue: make(chan model.Job),
  38. shutdown: make(chan struct{}),
  39. }
  40. for i := range nbWorkers {
  41. workerPool.wg.Add(1)
  42. worker := &worker{id: i, store: store}
  43. go worker.Run(workerPool.queue, workerPool.shutdown, &workerPool.wg)
  44. }
  45. return workerPool
  46. }