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.

GoData Integrity

Code

gosnippet
55 lines
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

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.