Share Mutex Structs Through Pointer Receivers

Embed sync.Mutex in a struct, call methods through pointer receivers, and join goroutines so multi-field state stays consistent and the lock is never copied.

GoData Integrity

Code

gosnippet
48 lines
package main

import (
	"fmt"
	"sync"
)

// Counter 用内嵌 sync.Mutex 保护两个字段的联动更新。
// 零值即可用(未加锁状态);含锁的值不可拷贝,共享必须走指针。
type Counter struct {
	mu    sync.Mutex
	total int
	calls int
}

func (c *Counter) Add(delta int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.total += delta
	c.calls++
}

// Snapshot 在同一个临界区内读取两个字段,保证看到的是一致状态
func (c *Counter) Snapshot() (int, int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.total, c.calls
}

func main() {
	var counter Counter // 零值即就绪,无需显式初始化
	// snapshot := counter // 拷贝含锁结构会被 go vet 判错,必须用 &counter

	var wg sync.WaitGroup
	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 25; j++ {
				counter.Add(1)
			}
		}()
	}
	wg.Wait()

	total, calls := counter.Snapshot()
	fmt.Println("total:", total, "calls:", calls)
}

How it works

Share Mutex Structs Through Pointer Receivers keeps everything in the functions Add, Snapshot and main.

Repetition is confined to for i := 0; i < 4; i++ — the rest of the file is straight-line. The task is handed to a goroutine and runs concurrently. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Using it

The signature doing the main work is func (c *Counter) Add(delta int)

The demo output is labeled (total:), so each line traces straight back to the statement that printed it.

The entry point wires Add and Snapshot together — run it once and the whole demo flows.

Key statements

func (c *Counter) Snapshot() (int, int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.total, c.calls
}
func (c *Counter) Add(delta int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.total += delta
	c.calls++
}
var wg sync.WaitGroup

Interactive Tools for This Topic

FAQ

What does Share Mutex Structs Through Pointer Receivers print when run?
Run it as a complete program — the output lines carry labels such as `total:`.