workers/workers.go

35 lines
659 B
Go
Raw Permalink Normal View History

2022-08-16 00:11:29 +00:00
package workers
import "sync"
// Channel launches n workers to perform an action for every item in the input channel
func Channel[T any](n int, ch chan T, handler func(T)) {
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
for item := range ch {
handler(item)
}
wg.Done()
}()
}
wg.Wait()
}
2023-12-24 03:20:25 +00:00
// Array launches n workers to perform an action for every item in the input array
func Array[T any](n int, arr []T, handler func(T)) {
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go func(i int) {
for j := 0; (j*n)+i < len(arr); j++ {
handler(arr[(j*n)+i])
}
wg.Done()
}(i)
}
wg.Wait()
}