Why does this code cause data race?

前端 未结 2 1057
被撕碎了的回忆
被撕碎了的回忆 2021-01-21 13:32
1 package main
2
3 import \"time\"
4
5 func main() {
6     m1 := make(map[string]int)
7     m1[\"hello\"] = 1
8     m1[\"world\"] = 2
9     go func() {
10         for i          


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-21 13:51

    Data race

    A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write.

    Instructions Reorder

    compilers and processors may reorder the reads and writes executed within a single goroutine as far as the reordering does not change the behaviour within the routine, it doesn' ensure behaviour of other goroutines to be unaffected

    m2["hello"] = 3
    m1 = m2
    

    Can be reordered to

    m1 = m2
    m2["hello"] = 3
    

    That won't alter the behaviour of the main routine and thus race checking will consider that also for evaluating race condition. Now we have m2["hello"] = 3 causing the race condition and it prints out the same with its original line number

提交回复
热议问题