Go

sync.Mutex vs sync.RWMutex

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`Mutex` allows one goroutine at a time — for both reads and writes. `RWMutex` allows multiple concurrent readers OR one writer — much better when reads dominate.
Go
Raw
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
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.