package main
import (
"fmt"
"sync"
)
type Counter struct {
mu sync.Mutex
count int
}
func (c *Counter) Inc() { c.mu.Lock(); defer c.mu.Unlock(); c.count++ }
func (c *Counter) Value() int { c.mu.Lock(); defer c.mu.Unlock(); return c.count }
// Read-heavy cache — RWMutex lets multiple readers proceed in parallel
type Cache struct {
mu sync.RWMutex
data map[string]string
}
func (c *Cache) Get(key string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock() // many readers may hold RLock concurrently
v, ok := c.data[key]
return v, ok
}
func (c *Cache) Set(key, val string) {
c.mu.Lock() // writer locks out all readers
defer c.mu.Unlock()
c.data[key] = val
}
func main() {
c := &Counter{}
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() { defer wg.Done(); c.Inc() }()
}
wg.Wait()
fmt.Println(c.Value()) // 1000
}
Create a free account and build your private vault. Share publicly whenever you want.