Request Reply Pattern With Per-Call Channels
Each query carries its own reply channel, so one worker goroutine owns the map exclusively and answers every caller without a mutex.
Code
package main
import (
"fmt"
"sync"
)
// 每个请求自带 reply channel:应答送回发起方而不是写共享结果
type query struct {
key string
reply chan string
}
// 单一 worker 独占 map:串行处理,无需任何锁
func serve(queries <-chan query) {
owners := map[string]string{
"a": "alice",
"b": "bob",
}
for q := range queries {
q.reply <- owners[q.key]
}
}
func main() {
queries := make(chan query)
go serve(queries)
var wg sync.WaitGroup
for _, key := range []string{"a", "b", "missing"} {
wg.Add(1)
go func(key string) {
defer wg.Done()
// 应答通道带 1 格缓冲:client 一定在等,worker 永不因回写阻塞
q := query{key: key, reply: make(chan string, 1)}
queries <- q
fmt.Printf("%s -> %q\n", key, <-q.reply)
}(key)
}
wg.Wait()
close(queries)
}How it works
Request Reply Pattern With Per-Call Channels keeps everything in the functions serve and main.
The loop for q := range queries is the only repeated construct. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.
Applying it
Entry signature: func serve(queries <-chan query)
Launch the file; main takes over and steps through serve.
Statements that matter
func serve(queries <-chan query) {
owners := map[string]string{
"a": "alice",
"b": "bob",
}
for q := range queries {
q.reply <- owners[q.key]
}
}
for _, key := range []string{"a", "b", "missing"} {
wg.Add(1)
go func(key string) {
defer wg.Done()
// 应答通道带 1 格缓冲:client 一定在等,worker 永不因回写阻塞
q := query{key: key, reply: make(chan string, 1)}
queries <- q
fmt.Printf("%s -> %q\n", key, <-q.reply)
}(key)
}
queries := make(chan query)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.
FAQ
- How do you run Request Reply Pattern With Per-Call Channels?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.