github.com/tiagovtristao/plz@v13.4.0+incompatible/src/core/pool.go (about) 1 package core 2 3 // A Pool implements an adjustable worker pool. 4 // We use it to handle parse tasks where we need to be able to deal with tasks blocking. 5 // Push onto the channel to submit new tasks. 6 type Pool chan func() 7 8 // NewPool constructs a new pool of the given size & starts its workers. 9 func NewPool(size int) Pool { 10 p := make(Pool) 11 for i := 0; i < size; i++ { 12 go p.Run() 13 } 14 return p 15 } 16 17 // Run is a worker function that consumes off the queue. 18 func (p Pool) Run() { 19 for f := range p { 20 if f == nil { 21 return // Poison message, indicates to stop 22 } 23 f() 24 } 25 } 26 27 // AddWorker adds a new worker to the pool. 28 func (p Pool) AddWorker() { 29 go p.Run() 30 } 31 32 // StopWorker indicates to a worker that it should stop. 33 func (p Pool) StopWorker() { 34 // Invoke in parallel so it doesn't block. 35 go func() { 36 p <- nil 37 }() 38 }