Map in Golang Part-II

Rajat Yadav
2 min readMar 20, 2021

In this article, we will study maps in goroutine.

Lets create a map and add key-values to it using goroutine.

Declare global variable to access over the program.

var m = make(map[string]int)

Read and Write operation on map in goroutines creates concurrency issues. Below code will create an error concurrent map write.

func main() {

// goroutine to write map
for i := 0; i<1000; i++ {
go WriteMap(i)
}
// goroutine to read map
for j := 0; j<1000; j++ {
go ReadMap(j)
}
}
func WriteMap(i int) {
str := "Key"
str = str + strconv.Itoa(i)
m[str] = i
}
func ReadMap(i int) {
str := "Key"
str = str + strconv.Itoa(i)
fmt.Println(m[str])
}

In the above example, func WriteMap will push the keys one by one. simultaneously func ReadMap will try to fetch the map against that key. Since the goroutine are used to achieve the concurrency, this may creates concurrent read write errors.

To solve the above generated errors, we can simple put the locks to the map.

Golang provide sync mutex to make sure only one goroutine can access a variable at a time to avoid conflicts.

var mutex = &sync.Mutex{}

The variable points the sync.Mutex struct having Lock() and Unlock() function.

Before read/write operation are performed on map, put locks on map and then unlock it.

mutex.Lock()
m[str] = i // write map
mutex.Unlock()
mutex.Lock()
_,found = m["pi"] // read map
mutex.Unlock()

You can run the above program on playground - Link

Next what?

Golang sync map in Goroutine…

Thank you !!! .. Feedback will be highly appreciated.

--

--