Lab 03: sync Package
Overview
Step 1: sync.Mutex — Exclusive Lock
package main
import (
"fmt"
"sync"
)
type SafeCounter struct {
mu sync.Mutex
v map[string]int
}
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.v[key]++
}
func (c *SafeCounter) Value(key string) int {
c.mu.Lock()
defer c.mu.Unlock()
return c.v[key]
}
func main() {
counter := &SafeCounter{v: make(map[string]int)}
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter.Inc("hits")
}()
}
wg.Wait()
fmt.Println("hits:", counter.Value("hits")) // always 1000
}Step 2: sync.RWMutex — Read-Write Lock
Step 3: sync.WaitGroup
Step 4: sync.Once — One-Time Initialization
Step 5: sync.Map — Concurrent Map
Step 6: Race Detector
Step 7: Combining Primitives
Step 8: Capstone — Thread-Safe LRU Cache Skeleton
Summary
Primitive
Use Case
Key Methods
Last updated
