Do atomic operations in the golang carry out the establishment of an incident?

I know what might happen that g prints 2 and then 0, given the following code.

var a, b uint32

func f() {
    a = 1
    b = 2
}

func g() {
    fmt.Println(b)
    fmt.Println(a)
}

func main() {
    go f()
    g()
}

What if I change all read and write operations to atomic operations? Is it guaranteed that if g first prints 2, then 1 also prints?

var a, b uint32

func f() {
    atomic.StoreUint32(&a, 1)
    atomic.StoreUint32(&b, 2)
}

func g() {
    fmt.Println(atomic.LoadUint32(&b))
    fmt.Println(atomic.LoadUint32(&a))
}

func main() {
    go f()
    g()
}
+4
source share
2 answers

No. There is no synchronization, so there is no "before before" .

Synchronization between goroutines is done through the channel link and lock operation.

Key point in the memory model:

goroutine , , . , , , goroutine, . - , , , . , goroutine a = 1; b = 2;, b a.

+2

Source: https://habr.com/ru/post/1669719/


All Articles