实现说明
把共享状态收敛到唯一的 owner goroutine以函数 main为骨架。
重复被限制在 for 里——其余代码按顺序各跑一遍。这里的并发就是一个 goroutine 加一个 channel——最小安全交接模式。清理逻辑用 defer 挂载,函数的任何退出路径都会执行。
使用要点
- 跑完文件,输出里会留下标记——
set ack:、total hits:。
常见问题
运行「把共享状态收敛到唯一的 owner goroutine」会打印什么?
运行文件本身,set ack:、total hits: 这些前缀各对应一段演示逻辑。
核心语句
req.reply <- fmt.Sprintf("%s=%d", req.key, counts[req.key])
sets <- setReq{key: "hits", value: i, reply: reply}
gets <- getReq{key: "hits", reply: reply}
代码示例
package main
import (
"fmt"
"sync"
)
// setReq:写请求与应答通道一起投递
type setReq struct {
key string
value int
reply chan string
}
// getReq:读请求同样带应答通道
type getReq struct {
key string
reply chan int
}
func main() {
sets := make(chan setReq)
gets := make(chan getReq)
// confinement:shared state 只属于这一个 owner goroutine,
// map 不暴露、不加锁,所有访问收敛成消息
go func() {
counts := make(map[string]int)
for {
select {
case req := <-sets:
counts[req.key] += req.value
req.reply <- fmt.Sprintf("%s=%d", req.key, counts[req.key])
case req := <-gets:
req.reply <- counts[req.key]
}
}
}()
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
reply := make(chan string, 1)
sets <- setReq{key: "hits", value: i, reply: reply}
fmt.Println("set ack:", <-reply)
}(i)
}
wg.Wait()
reply := make(chan int, 1)
gets <- getReq{key: "hits", reply: reply}
fmt.Println("total hits:", <-reply)
}