How to Implement the Reader-Writer Lock Pattern in Go

Implement the Reader-Writer lock pattern in Go using sync.RWMutex to manage concurrent read and write access safely.

Use sync.RWMutex to allow multiple concurrent readers or a single exclusive writer. Create a struct embedding sync.RWMutex, then call RLock()/RUnlock() for reads and Lock()/Unlock() for writes.

package main

import (
	"sync"
)

type DataStore struct {
	mu   sync.RWMutex
	data map[string]int
}

func (s *DataStore) Read(key string) int {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.data[key]
}

func (s *DataStore) Write(key string, val int) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data[key] = val
}