Go

Worker Pool with Channels

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Spawn N worker goroutines, feed them tasks over a jobs channel, collect results on a results channel. Idiomatic Go pattern for bounded concurrency.
Go
Raw
package main

import (
    "fmt"
    "sync"
)

func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()
    for j := range jobs {
        results <- j * j                       // pretend this is expensive
        _ = id
    }
}

func main() {
    const numJobs    = 20
    const numWorkers = 4

    jobs    := make(chan int,    numJobs)
    results := make(chan int,    numJobs)

    var wg sync.WaitGroup
    for w := 1; w <= numWorkers; w++ {
        wg.Add(1)
        go worker(w, jobs, results, &wg)
    }

    // Send all jobs
    for j := 1; j <= numJobs; j++ { jobs <- j }
    close(jobs)                                 // tells workers "no more"

    // Wait for workers in a separate goroutine, then close results
    go func() { wg.Wait(); close(results) }()

    for r := range results {
        fmt.Println(r)
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.