Skip to content

Instantly share code, notes, and snippets.

@echohes
Created March 18, 2021 08:13
Show Gist options
  • Save echohes/b2e5eb6c803659124a76418d10430410 to your computer and use it in GitHub Desktop.
Save echohes/b2e5eb6c803659124a76418d10430410 to your computer and use it in GitHub Desktop.
go sync.map example
package main
import (
"fmt"
"sync"
"time"
)
var arrTest = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var minicache sync.Map
func towrite(text string) {
for _, v := range arrTest {
minicache.Store(v, text)
time.Sleep(10 * time.Millisecond)
}
}
func main() {
go towrite("test1")
go towrite("test2")
go func() {
time.Sleep(10 * time.Millisecond)
for _, v := range arrTest {
if val, ok := minicache.Load(v); ok {
fmt.Println(v, val)
} else {
fmt.Println(v, "not get")
}
time.Sleep(10 * time.Millisecond)
}
}()
time.Sleep(10 * time.Second)
}
@echohes
Copy link
Author

echohes commented Mar 18, 2021

If you use just a global map without syncmap and decrease timeout, the compiler will generate the error "fatal error: concurrent map writes"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment