Last active
February 4, 2020 11:18
-
-
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.
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 | |
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