Hands-On: Go Channels as In-Process Queues (stdlib)
This demonstrates fan-out workers with Go channels using no external libraries:
xxxxxxxxxx
35
}
package main
import (
"fmt"
"math/rand"
"time"
)
func worker(id int, jobs <-chan int, results chan<- string) {
for j := range jobs {
// do work
time.Sleep(time.Millisecond * time.Duration(20+rand.Intn(20)))
results <- fmt.Sprintf("worker %d done job %d", id, j)
}
}
func main() {
jobs := make(chan int, 8) // buffer = backpressure control
results := make(chan string)
// spin up consumers
for w := 1; w <= 3; w++ { go worker(w, jobs, results) }
// produce jobs
go func() {
for j := 1; j <= 12; j++ { jobs <- j }
close(jobs) // no more work
}()
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment