Created
October 12, 2020 07:01
-
-
Save hallazzang/4afdfcb4e95a65a132e4d59314214a89 to your computer and use it in GitHub Desktop.
Fixed number worker pool implementation #1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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