Skip to content

Instantly share code, notes, and snippets.

@ashishtiwari1993
Last active February 4, 2020 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashishtiwari1993/d494b71ac264184ba46ced1bf2114c30 to your computer and use it in GitHub Desktop.
Save ashishtiwari1993/d494b71ac264184ba46ced1bf2114c30 to your computer and use it in GitHub Desktop.
Reproduce Golang "fatal error: concurrent map writes" & Solution. To reproduce comment Mutex related all operation like line no. 12, 30, 32, 44, 46. Mutex is use to prevent race condition which generates this error.
package main
import (
"fmt"
"sync"
// "time"
"strconv"
)
var activeInstances = make(map[int]string)
var wg sync.WaitGroup
var mutex = &sync.Mutex{}
func main(){
wg.Add(2)
go setValue()
go deleteValue()
wg.Wait()
}
func setValue(){
i := 0;
for {
// time.Sleep(1 * time.Second)
fmt.Println("In setValue(). Iteration = " + strconv.Itoa(i) + "\n")
mutex.Lock()
activeInstances[i] = "In setValue string"
mutex.Unlock()
i++
}
}
func deleteValue(){
i := 0;
for {
// time.Sleep(1 * time.Second)
fmt.Println("In deleteValue(). Iteration = " + strconv.Itoa(i) + "\n")
mutex.Lock()
delete(activeInstances, i)
mutex.Unlock()
i++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment