Skip to content

Instantly share code, notes, and snippets.

@mndrix
Created March 3, 2017 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mndrix/b3d3964f56c88e6694e6766229f76d2e to your computer and use it in GitHub Desktop.
Save mndrix/b3d3964f56c88e6694e6766229f76d2e to your computer and use it in GitHub Desktop.
Can multiple goroutines read from a single map?
package main
// "go run -race read-race.go"
import (
"fmt"
"sync"
)
func main() {
fmt.Println("starting goroutines")
var wg sync.WaitGroup
m := map[string]int{"hola": 42}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() { defer wg.Done()
for i := 0; i < 10000000; i++ {
x := m["hola"]
if x != 42 {
panic("read something crazy")
}
if i == 973 {
// uncomment to show that writes cause races
//m["elsewhere"] = 7
}
}
}()
}
wg.Wait()
fmt.Println("all done")
}
@mndrix
Copy link
Author

mndrix commented Mar 3, 2017

If goroutines only read from a map and nobody is writing to it, concurrent access is OK. As soon as someone modifies the map, concurrency causes trouble and needs synchronization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment