Created
March 3, 2017 14:07
-
-
Save mndrix/b3d3964f56c88e6694e6766229f76d2e to your computer and use it in GitHub Desktop.
Can multiple goroutines read from a single map?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.