Confine Shared State To An Owner Goroutine
Let one owner goroutine exclusively own a map and serve set and get requests over channels, the confinement idiom that replaces locks with message passing.
Code
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)
}Inside the snippet
Confine Shared State To An Owner Goroutine is built around the function main.
The cycling part of this snippet is for. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. The cleanup call is deferred to function exit — success, early return, and panic all covered.
Using it
Running the file prints labeled results such as set ack:, total hits: — each operation’s effect is visible in the output.
Key statements
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}
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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Confine Shared State To An Owner Goroutine print when run?
- No setup needed: run the file and look for labeled lines like `set ack:`, `total hits:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.