package main import ( "sync" ) var ( data = make(map[string]string) rw = &sync.RWMutex{} ) func read(key string) string { rw.RLock() defer rw.RUnlock() return data[key] } func write(key, value string) { rw.Lock() defer rw.Unlock() data[key] = value } func main() { // Concurrent read access go read("foo") go read("bar") // Concurrent write and read access go write("baz", "qux") go read("baz") }
package main import ( "sync" ) type Cache struct { data map[string]string rw sync.RWMutex } func (c *Cache) Get(key string) string { // Check if value is already in cache c.rw.RLock() value, ok := c.data[key] c.rw.RUnlock() if ok { return value } // Value not in cache, acquire write lock and load from database c.rw.Lock() defer c.rw.Unlock() // Check again if value was loaded by another thread while waiting for the lock value, ok = c.data[key] if ok { return value } // Load value from database and add to cache value = loadFromDatabase(key) c.data[key] = value return value } func loadFromDatabase(key string) string { // Simulate loading from database by returning a placeholder value return "value for " + key } func main() { c := &Cache{data: make(map[string]string)} go c.Get("foo") go c.Get("bar") go c.Get("foo") }In this example, we implement a Cache struct that holds a map of cached values. When a value is requested using `Get`, we first check if it is already in the cache. If it is, we return it immediately. If it is not, we acquire a write lock and load the value from the database before adding it to the cache. We use a write lock to ensure that only one thread loads a value for a given key. We use a read lock to allow multiple threads to read the same value from the cache concurrently. Conclusion: The sync package in Go provides basic synchronization primitives such as mutexes and RWMutexes for concurrent programming. We can use the RWMutex to allow multiple readers to access shared data concurrently while ensuring exclusive access for writers. This can improve performance in scenarios where the frequency of reads is much higher than that of writes.