Created
March 18, 2021 08:13
-
-
Save echohes/b2e5eb6c803659124a76418d10430410 to your computer and use it in GitHub Desktop.
go sync.map example
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" | |
) | |
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you use just a global map without syncmap and decrease timeout, the compiler will generate the error "fatal error: concurrent map writes"