
The Secret Life of Go: The Mutex
Protecting Shared Memory and The RWMutex Part 27: Protecting Shared Memory and The RWMutex Ethan stared at his terminal, utterly defeated. "It panics," he said. "Every time I run the load test, the whole server crashes." Eleanor peered over his shoulder at the error message glowing on the screen: fatal error: concurrent map read and map write . "Ah," Eleanor nodded. "The classic map panic. Show me the cache implementation." Ethan brought up the code. var cache = make ( map [ string ] string ) func GetUser ( id string ) string { // If it's in the cache, return it if val , exists := cache [ id ]; exists { return val } // Simulate a database fetch data := fetchFromDB ( id ) // Save to cache for next time cache [ id ] = data return data } "I have dozens of goroutines calling GetUser at the same time," Ethan explained. "I thought Go was built for concurrency." "Go is," Eleanor said. "But its standard map is not thread-safe. When one goroutine is writing to the map ( cache[id] = data ), and
Continue reading on Dev.to
Opens in a new tab

