Skip to content

Instantly share code, notes, and snippets.

@iamspark1e
Forked from harlow/worker-pool.go
Created October 20, 2022 09:00
Show Gist options
  • Save iamspark1e/216774d7de0ef4b62a72aa6bb9cb843e to your computer and use it in GitHub Desktop.
Save iamspark1e/216774d7de0ef4b62a72aa6bb9cb843e to your computer and use it in GitHub Desktop.
Worker pool to control concurrency and collect results
package main
import (
"fmt"
"sync"
"time"
)
const concurrency = 3
func main() {
// put tasks on channel
tasks := make(chan int, 100)
go func() {
for j := 1; j <= 9; j++ {
tasks <- j
}
close(tasks)
}()
// waitgroup, and close results channel when work done
results := make(chan int)
wg := &sync.WaitGroup{}
wg.Add(concurrency)
go func() {
wg.Wait()
close(results)
}()
for i := 1; i <= concurrency; i++ {
go func(id int) {
defer wg.Done()
for t := range tasks {
fmt.Println("worker", id, "processing job", t)
results <- t * 2
time.Sleep(time.Second)
}
}(i)
}
// loop over results until closed (see above)
for r := range results {
fmt.Println("result", r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment