Challenge: Implement Race Condition on a Map in Go
Problem Statement
- Create one function that will read the value of the data and one function that will update the value.
- Place them inside goroutines to make both of them run concurrently.
- Add a
time.Sleep
function at the end to ensure that themain
goroutine doesn’t exit.
💡
Note: The time.Sleep function is just a workaround. Don’t use it to make your main goroutine complete its functions. Instead, use WaitGroup.
Solution
Create a main.go
file in your directory. Add the below code.
package main
import (
"time"
)
func read(sharedMap map[int]int) {
for {
_ = sharedMap[0]
}
}
func write(sharedMap map[int]int) {
for {
sharedMap[0] = sharedMap[0] + 1
}
}
func main() {
sharedMap := make(map[int]int)
sharedMap[0] = 0
go read(sharedMap)
go write(sharedMap)
time.Sleep(2 * time.Second)
}
To test this code, fire go run .
in your terminal to see the output.
fatal error: concurrent map read and map write
You’ll get the error fatal error: concurrent map read and map write
if you execute the above code widget because read
and write
goroutines are accessing the sharedMap
variable at the same time.