Lab 14: Goroutine Patterns
Overview
Step 1: Worker Pool Pattern
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for j := range jobs {
// Simulate work
time.Sleep(time.Millisecond)
results <- j * j // return square of job number
}
}
func main() {
const numJobs = 20
const numWorkers = 5
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
var wg sync.WaitGroup
// Spawn fixed pool of workers
for w := 1; w <= numWorkers; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
// Send all jobs, then close to signal no more work
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
// Wait for all workers, then close results
go func() {
wg.Wait()
close(results)
}()
// Collect results
sum := 0
for r := range results {
sum += r
}
fmt.Printf("Worker pool: processed %d jobs with %d workers\n", numJobs, numWorkers)
fmt.Printf("Sum of squares 1..%d = %d\n", numJobs, sum)
}Step 2: Pipeline Pattern
Step 3: Bounded Concurrency with Semaphore
Step 4: errgroup for Parallel Error Collection
errgroup for Parallel Error CollectionStep 5: Graceful Shutdown with Context + WaitGroup
Step 6: Fan-Out / Fan-In
Step 7: Common Mistakes to Avoid
Step 8 (Capstone): Complete Worker Pool with 100 Jobs
Summary
Pattern
Implementation
Use Case
Last updated
