navidrome/utils/pool/pool.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

91 lines
1.5 KiB
Go
Raw Normal View History

package pool
2020-10-30 21:08:43 +01:00
import (
"time"
"github.com/navidrome/navidrome/log"
)
type Executor func(workload interface{})
type Pool struct {
2020-12-16 02:46:52 +01:00
name string
workers []worker
exec Executor
queue chan work // receives jobs to send to workers
done chan bool // when receives bool stops workers
working bool
}
// TODO This hardcoded value will go away when the queue is persisted in disk
const bufferSize = 10000
2020-12-16 02:46:52 +01:00
func NewPool(name string, workerCount int, exec Executor) (*Pool, error) {
p := &Pool{
2020-12-16 02:46:52 +01:00
name: name,
exec: exec,
queue: make(chan work, bufferSize),
done: make(chan bool),
working: false,
}
for i := 0; i < workerCount; i++ {
worker := worker{
2020-12-16 02:46:52 +01:00
p: p,
id: i,
}
worker.Start()
p.workers = append(p.workers, worker)
}
go func() {
2020-12-16 02:46:52 +01:00
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
2020-12-16 02:46:52 +01:00
case <-ticker.C:
2020-10-30 21:08:43 +01:00
if len(p.queue) > 0 {
2020-12-16 02:46:52 +01:00
log.Debug("Queue status", "poolName", p.name, "items", len(p.queue))
2020-10-30 21:08:43 +01:00
} else {
2020-12-16 02:46:52 +01:00
if p.working {
log.Info("Queue is empty, all items processed", "poolName", p.name)
2020-10-30 21:08:43 +01:00
}
2020-12-16 02:46:52 +01:00
p.working = false
}
2020-12-16 02:46:52 +01:00
case <-p.done:
close(p.queue)
return
}
}
}()
2020-12-16 02:46:52 +01:00
return p, nil
}
func (p *Pool) Submit(workload interface{}) {
2020-12-16 02:46:52 +01:00
p.working = true
p.queue <- work{workload}
}
2021-01-04 00:16:37 +01:00
func (p *Pool) Stop() {
p.done <- true
}
type work struct {
workload interface{}
}
type worker struct {
2020-12-16 02:46:52 +01:00
id int
p *Pool
}
// start worker
func (w *worker) Start() {
go func() {
2020-12-16 02:46:52 +01:00
for job := range w.p.queue {
w.p.exec(job.workload) // do work
}
}()
}