← Project templates

BASICS · IN THE APP NOW

Worker pool

Three workers square five jobs. The program shows who closes which channel, and when.

Offline: standard library only

Open it in the browser Playground →

What it is

The sender closes jobs once every job is queued, which ends each worker's range loop. Only after workers.Wait returns is results closed, so the final loop drains it and stops. Results can arrive in any order.

Every template's Go program was compiled for GOOS=wasip1 GOARCH=wasm with Go 1.27, then run, vetted and tested before it was added to the app.

Files

text
worker-pool/
├── go.mod
└── main.go

The code

main.go

go
package main

import (
	"fmt"
	"sync"
)

func main() {
	jobs := make(chan int, 8)
	results := make(chan int, 8)

	var workers sync.WaitGroup
	for worker := 1; worker <= 3; worker++ {
		workers.Add(1)
		go func(id int) {
			defer workers.Done()
			for job := range jobs {
				results <- job * job
			}
		}(worker)
	}

	for job := 1; job <= 5; job++ {
		jobs <- job
	}
	close(jobs)

	workers.Wait()
	close(results)

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

What you learn

  • Start a fixed number of goroutines that range over a shared jobs channel.
  • Use sync.WaitGroup with Add before go and Done in a defer.
  • Close a channel from the sending side only, and close results after the workers finish.
  • Size buffered channels so the example cannot deadlock.

Run it on a server

On a computer you can also run it under the race detector, which the phone sandbox does not provide.

bash
go run .
go run -race .

Related: The worker pool, written once · Concurrency unit