typestar

Worker pools in Go

A fixed set of goroutines draining a job channel.

func pool(jobs <-chan int, workers int) <-chan int {
    results := make(chan int)
    var wg sync.WaitGroup
    for i := 0; i < workers; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for j := range jobs {
                results <- j * j
            }
        }()
    }
    go func() {
        wg.Wait()
        close(results)
    }()
    return results
}

How it works

  1. Every worker ranges over the same jobs channel.
  2. A closer goroutine waits then closes results.
  3. The main goroutine collects until results close.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
274
Tokens
92
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 50 seconds.

Type this snippet

Step 1 of 5 in Patterns, step 19 of 25 in Concurrency.

← Previous Next →