Mutex Protecting Shared State
Guard a shared map with sync.RWMutex so concurrent readers proceed together while writers stay exclusive.
Code
package main
import (
"fmt"
"sync"
)
type Counter struct {
mu sync.RWMutex
values map[string]int
}
func NewCounter() *Counter {
return &Counter{values: make(map[string]int)}
}
func (c *Counter) Inc(key string) {
c.mu.Lock() // 写锁:独占
defer c.mu.Unlock()
c.values[key]++
}
func (c *Counter) Get(key string) int {
c.mu.RLock() // 读锁:可并发
defer c.mu.RUnlock()
return c.values[key]
}
func main() {
c := NewCounter()
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
c.Inc("hits")
}()
}
// 并发读与写交错执行,读锁不互斥
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_ = c.Get("hits")
}()
}
wg.Wait()
fmt.Println("hits:", c.Get("hits"))
}How it works
Count the functions NewCounter, Inc, Get and main as the entire surface area of Mutex Protecting Shared State.
Iteration happens inside for i := 0; i < 100; i++ — everything outside it runs once. Work is dispatched on a goroutine. Cleanup is attached with defer, so it runs on every exit path of the function.
Applying it
Entry signature: func NewCounter() *Counter
Running the file prints labeled results such as hits: — each operation’s effect is visible in the output.
The demo flow inside main is NewCounter, Inc and Get — run the file to see it end to end.
Statements that matter
return &Counter{values: make(map[string]int)}
func (c *Counter) Get(key string) int {
c.mu.RLock() // 读锁:可并发
defer c.mu.RUnlock()
return c.values[key]
}
func (c *Counter) Inc(key string) {
c.mu.Lock() // 写锁:独占
defer c.mu.Unlock()
c.values[key]++
}
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 Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Mutex Protecting Shared State print when run?
- Invoke the file as-is — the `hits:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.