Back to listGo
Go Worker Pool Pattern
Lv.5808@mukitaro12 playsDec 28, 2025
Go worker pool pattern using channels and goroutines for concurrent job processing.
preview.go
1package main2 3import (4 "fmt"5 "sync"6 "time"7)8 9type Job struct {10 ID int11 Data string12}13 14type Result struct {15 JobID int16 Output string17}18 19func worker(id int, jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {20 defer wg.Done()21 for job := range jobs {22 time.Sleep(100 * time.Millisecond)23 results <- Result{24 JobID: job.ID,25 Output: fmt.Sprintf("Worker %d processed: %s", id, job.Data),26 }27 }28}29 30func main() {31 jobs := make(chan Job, 10)32 results := make(chan Result, 10)33 var wg sync.WaitGroup34 35 for w := 1; w <= 3; w++ {36 wg.Add(1)37 go worker(w, jobs, results, &wg)38 }39 40 for j := 1; j <= 5; j++ {41 jobs <- Job{ID: j, Data: fmt.Sprintf("Task %d", j)}42 }43 close(jobs)44 45 go func() {46 wg.Wait()47 close(results)48 }()49 50 for result := range results {51 fmt.Println(result.Output)52 }53}Custom problems are not included in rankings