Skip to content

Instantly share code, notes, and snippets.

@abdivasiyev
Last active May 22, 2024 21:16
Show Gist options
  • Save abdivasiyev/a4b29afa86a0c8a3f5839d330fe1d9d6 to your computer and use it in GitHub Desktop.
Save abdivasiyev/a4b29afa86a0c8a3f5839d330fe1d9d6 to your computer and use it in GitHub Desktop.
Goroutine management by using workerpool pattern
package workerpool
type Work[T any] func(workerID int, result chan<- T) error
type Pool[T any] interface {
Add(w Work[T])
Shutdown()
Result() <-chan T
}
type pool[T any] struct {
maxWorkers int
resultChan chan T
workerChan chan Work[T]
}
func (p *pool[T]) Add(w Work[T]) {
p.workerChan <- w
}
func (p *pool[T]) Result() <-chan T {
return p.resultChan
}
func (p *pool[T]) Shutdown() {
close(p.workerChan)
close(p.resultChan)
}
func (p *pool[T]) run() {
for i := 0; i < p.maxWorkers; i++ {
go func(workerID int) {
for w := range p.workerChan {
w(workerID, p.resultChan)
}
}(i)
}
}
func New[T any](maxWorkers int) Pool[T] {
p := &pool[T]{
maxWorkers: maxWorkers,
workerChan: make(chan Work[T], maxWorkers),
resultChan: make(chan T, maxWorkers),
}
p.run()
return p
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment