Creating map for concurrent access
The map primitive in Golang should be considered as unsafe for concurrent access. In the previous recipe, we described how to synchronize access to the resource with Mutex, which could also be leveraged with access to the map primitive. But the Go standard library also provides the map structure designed for concurrent access. This recipe will illustrate how to work with it.
How to do it...
- Open the console and create the folder
chapter10/recipe02
. - Navigate to the directory.
- Create the file
map.go
with the following content:
package main import ( "fmt" "sync" ) var names = []string{"Alan", "Joe", "Jack", "Ben", "Ellen", "Lisa", "Carl", "Steve", "Anton", "Yo"} func main() { m := sync.Map{} wg := &sync.WaitGroup{} wg.Add(10) for i := 0; i < 10; i++ { go func(idx int) { ...