Skip to content

Instantly share code, notes, and snippets.

@hallazzang
Created October 12, 2020 07:01
Show Gist options
  • Save hallazzang/4afdfcb4e95a65a132e4d59314214a89 to your computer and use it in GitHub Desktop.
Save hallazzang/4afdfcb4e95a65a132e4d59314214a89 to your computer and use it in GitHub Desktop.
Fixed number worker pool implementation #1
type Pool struct {
n int
run func(context.Context)
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
}
func NewPool(n int, run func(context.Context)) *Pool {
ctx, cancel := context.WithCancel(context.Background())
return &Pool{
n: n,
run: run,
ctx: ctx,
cancel: cancel,
}
}
func (p *Pool) Start() {
for i := 0; i < p.n; i++ {
go p.launch()
}
}
func (p *Pool) launch() {
p.wg.Add(1)
defer p.wg.Done()
defer func() {
select {
case <-p.ctx.Done():
default:
go p.launch()
}
}()
p.run(p.ctx)
}
func (p *Pool) Stop() {
p.cancel()
}
func (p *Pool) Wait() {
<-p.ctx.Done()
p.wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment