Concurrency Patterns
Worker Pool
package main
import (
"fmt"
"sync"
)
// Job represents a task that can be executed by a worker.
type Job struct {
ID int
}
func main() {
// Number of worker goroutines in the pool.
numWorkers := 3
// Create a task channel to send jobs to workers.
tasks := make(chan Job, 10)
// Create a wait group to wait for all workers to finish.
var wg sync.WaitGroup
// Create and start worker goroutines.
for i := 1; i <= numWorkers; i++ {
wg.Add(1)
go worker(i, tasks, &wg)
}
// Add jobs to the task channel.
for i := 1; i <= 5; i++ {
tasks <- Job{ID: i}
}
// Close the task channel to signal that no more jobs will be added.
close(tasks)
// Wait for all workers to finish.
wg.Wait()
}
// worker is a function that represents a worker goroutine.
func worker(id int, tasks <-chan Job, wg *sync.WaitGroup) {
defer wg.Done()
for task := range tasks {
fmt.Printf("Worker %d is processing job %d\n", id, task.ID)
// Simulate some work by sleeping.
// In a real application, you would perform the actual task here.
}
}
Fan-out/Fan-in
Last updated