Last active
May 16, 2023 08:47
-
-
Save sashaaro/dba53499d65a9a7d7d80d88494da36c2 to your computer and use it in GitHub Desktop.
golang simple workers pool
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
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