golang map 锁_golang中多goroutine操作map时直接赋值不用加锁?

@Terry-Mao

通过golang race detector检查,显示有data race

代码:

1 package main

2 import (

3 "math/rand"

4 "strconv"

5 "sync"

6 )

7

8 func main() {

9 map1 := make(map[string]int)

10 map1["100"] = 100

11 var wg sync.WaitGroup

12 wg.Add(1)

13 go func() {

14 for i := 0; i < 10000000; i++ {

15 map2 := make(map[string]int)

16 j := rand.Intn(30)

17 for k := 0; k < j; k++ {

18 map2[strconv.Itoa(k)] = k

19 }

20 map1 = map2

21 }

22 wg.Done()

23 }()

24 for i := 0; i < 10; i++ {

25 wg.Add(1)

26 go func() {

27 for i := 0; i < 1000000; i++ {

28 _, _ = map1["2"]

29 }

30 wg.Done()

31 }()

32 }

33 wg.Wait()

34 }

race结果

root@ubuntu:/home# go run -race test.go

==================

WARNING: DATA RACE

Read by goroutine 6:

main.main.func2()

/home/test.go:28 +0x56

Previous write by goroutine 5:

main.main.func1()

/home/test.go:20 +0x109

Goroutine 6 (running) created at:

main.main()

/home/test.go:31 +0x1b7

Goroutine 5 (running) created at:

main.main()

/home/test.go:23 +0x167

==================

==================

WARNING: DATA RACE

Read by goroutine 6:

runtime.mapaccess2_faststr()

/root/go/src/runtime/hashmap_fast.go:298 +0x0

main.main.func2()

/home/test.go:28 +0x87

Previous write by goroutine 5:

runtime.mapassign1()

/root/go/src/runtime/hashmap.go:429 +0x0

main.main.func1()

/home/test.go:18 +0xe9

Goroutine 6 (running) created at:

main.main()

/home/test.go:31 +0x1b7

Goroutine 5 (running) created at:

main.main()

/home/test.go:23 +0x167

==================

==================

WARNING: DATA RACE

Read by goroutine 7:

runtime.mapaccess2_faststr()

/root/go/src/runtime/hashmap_fast.go:298 +0x0

main.main.func2()

/home/test.go:28 +0x87

Previous write by goroutine 5:

runtime.mapassign1()

/root/go/src/runtime/hashmap.go:429 +0x0

main.main.func1()

/home/test.go:18 +0xe9

Goroutine 7 (running) created at:

main.main()

/home/test.go:31 +0x1b7

Goroutine 5 (running) created at:

main.main()

/home/test.go:23 +0x167

==================

你可能感兴趣的:(golang,map,锁)