Round Robin Dispatch Across Channels
Distribute work cyclically over one channel per worker with round-robin indexing, so each goroutine owns a private queue instead of contending on one.
Code
package main
import (
"fmt"
"sync"
)
func worker(name string, jobs <-chan string, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
fmt.Printf("%s handled %s\n", name, job)
}
}
func main() {
const workers = 3
queues := make([]chan string, workers)
var wg sync.WaitGroup
for i := range queues {
queues[i] = make(chan string)
wg.Add(1)
go worker(fmt.Sprintf("worker-%d", i), queues[i], &wg)
}
// 轮转派发:i%workers 让每个 worker 拿到自己的私有队列
tasks := []string{"a", "b", "c", "d", "e", "f", "g"}
for i, task := range tasks {
queues[i%workers] <- task
}
for _, ch := range queues {
close(ch)
}
wg.Wait()
}One private queue per worker
main builds workers = 3 channels, starts one worker goroutine per channel (go worker(fmt.Sprintf("worker-%d", i), queues[i], &wg)), and dispatches the seven tasks with queues[i%workers] <- task. No shared queue exists: each goroutine drains only its own channel, so there is no contention point and each worker’s assignment is fixed by arithmetic.
Who gets which task
With i%3 over ["a","b","c","d","e","f","g"]: worker-0 receives a, d, g; worker-1 receives b, e; worker-2 receives c, f. Each worker prints its own jobs in that order — fmt.Printf("%s handled %s\n", name, job) — but the interleaving of lines across the three goroutines is not deterministic run to run, so only the per-worker pairing is a stable fact. After dispatch, main closes every queue with for _, ch := range queues { close(ch) }, and worker’s for job := range jobs loop ends when its channel closes; defer wg.Done() releases the WaitGroup on every exit path.
The line that cycles the queues
queues[i%workers] <- task
The modulo index is the entire strategy — task 7 lands on worker 7%3 = 1 without any counter state, and adding a fourth worker changes only the workers constant.
Interactive Tools for This Topic
FAQ
- How do you run Round Robin Dispatch Across Channels?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.