Last active
February 3, 2024 04:05
-
-
Save crazyoptimist/1d63c9bb6edd3df7ff3fc8343b8c1281 to your computer and use it in GitHub Desktop.
Worker Pool Concurrency Pattern in Go
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 main | |
import ( | |
"fmt" | |
"sync" | |
) | |
const ( | |
NUM_WORKERS = 10 | |
NUM_JOBS = 10000 | |
) | |
func main() { | |
jobs := make(chan int) | |
var wg sync.WaitGroup | |
go Run(jobs, &wg) | |
Dispatch(jobs, &wg) | |
wg.Wait() | |
} | |
func Dispatch(jobs chan<- int, wg *sync.WaitGroup) { | |
defer close(jobs) | |
for i := 1; i <= NUM_JOBS; i++ { | |
wg.Add(1) | |
fmt.Printf("Sending %d\n", i) | |
jobs <- i | |
} | |
} | |
func Run(jobs <-chan int, wg *sync.WaitGroup) { | |
for i := 1; i <= NUM_WORKERS; i++ { | |
// Spin up a new worker | |
k := i | |
go func() { | |
for job := range jobs { | |
fmt.Printf("%d th Worker received %d\n", k, job) | |
wg.Done() | |
} | |
}() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment