Go 更改地图链接是否安全?
您知道吗,在并发环境中将map变量链接更改为另一个是否安全 例如,一个goroutine中的mapGo 更改地图链接是否安全?,go,concurrency,Go,Concurrency,您知道吗,在并发环境中将map变量链接更改为另一个是否安全 例如,一个goroutine中的mapdata替换为新map,并从另一个goroutine中读取元素: import ( "fmt" "math/rand" "strconv" "testing" "time" ) func TestMap(t *testing.T) { s1 := ra
data
替换为新map,并从另一个goroutine中读取元素:
import (
"fmt"
"math/rand"
"strconv"
"testing"
"time"
)
func TestMap(t *testing.T) {
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
data := fill(r1.Intn(100))
timer := time.NewTimer(10 * time.Second)
go func() {
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
for {
select {
case <-timer.C:
return
default:
}
p := r1.Intn(100)
v := fill(p)
data = v
fmt.Println("_p=" + strconv.Itoa(p))
}
}()
for range []int{1, 2, 3, 4, 5, 6, 7, 8} {
go func() {
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
for {
select {
case <-timer.C:
return
default:
}
n := r1.Intn(100)
s := strconv.Itoa(n)
fmt.Println(data[s])
}
}()
}
<-timer.C
}
func fill(postfix int) map[string][]string {
m := make(map[string][]string)
for i := 0; i < 100; i++ {
s := strconv.Itoa(i)
m[s] = []string{s + "_" + strconv.Itoa(postfix)}
}
return m
}
导入(
“fmt”
“数学/兰德”
“strconv”
“测试”
“时间”
)
func TestMap(t*testing.t){
s1:=rand.NewSource(time.Now().UnixNano())
r1:=新兰特(s1)
数据:=填充(r1.Intn(100))
计时器:=时间。新计时器(10*时间。秒)
go func(){
s1:=rand.NewSource(time.Now().UnixNano())
r1:=新兰特(s1)
为了{
挑选{
case当然不安全。没有变量(包括map)对并发读写是安全的
您的一个goroutine写入数据
,另一个读取数据。使用go test-race
运行测试也会报告数据竞争:
testing.go:954: race detected during execution of test
您必须同步读取和写入多个goroutine中的数据变量。不是,请在更新数据时使用sync.Mutex将其锁定和解锁