加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

内存 – golang中的原子操作是否建立了先发生关系?

发布时间:2020-12-16 09:25:52 所属栏目:大数据 来源:网络整理
导读:我知道可以发生g打印2然后给出以下代码0. var a,b uint32func f() { a = 1 b = 2}func g() { fmt.Println(b) fmt.Println(a)}func main() { go f() g()} 如果我将所有读写更改为原子操作怎么办?是否保证如果g先打印2,那么还会打印1? var a,b uint32func f(
我知道可以发生g打印2然后给出以下代码0.

var a,b uint32

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

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

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

如果我将所有读写更改为原子操作怎么办?是否保证如果g先打印2,那么还会打印1?

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()
}

解决方法

没有.没有同步,所以没有 “happens before”的关系.

goroutines之间的Synchronization是通过通道通信和锁定操作完成的.

内存模型中的关键段落是:

Within a single goroutine,reads and writes must behave as if they executed in the order specified by the program. That is,compilers and processors may reorder the reads and writes executed within a single goroutine only when the reordering does not change the behavior within that goroutine as defined by the language specification. Because of this reordering,the execution order observed by one goroutine may differ from the order perceived by another. For example,if one goroutine executes a = 1; b = 2;,another might observe the updated value of b before the updated value of a.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读