Skip to content

Instantly share code, notes, and snippets.

@sashaaro
Last active May 16, 2023 08:47
Show Gist options
  • Save sashaaro/dba53499d65a9a7d7d80d88494da36c2 to your computer and use it in GitHub Desktop.
Save sashaaro/dba53499d65a9a7d7d80d88494da36c2 to your computer and use it in GitHub Desktop.
golang simple workers pool
package utils
type WorkerPool[T any] struct {
workFn func(jobID int, result chan<- T)
result chan T
}
func NewWorkerPool[T any]() WorkerPool[T] {
pool := WorkerPool[T]{}
pool.result = make(chan T)
return pool
}
func (pool WorkerPool[T]) Run(goroutinWorkers int, jobLimit int, workFn func(jobID int, result chan<- T)) <-chan T {
jobs := make(chan int)
pool.workFn = workFn
for i := 0; i < goroutinWorkers; i++ {
go pool.work(jobs)
}
go func() {
for i := 0; i < jobLimit; i++ {
jobs <- i
}
close(jobs)
}()
return pool.result
}
func (pool WorkerPool[T]) work(jobs <-chan int) {
for jobID := range jobs {
pool.workFn(jobID, pool.result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment