duanchijie2323 2018-06-20 08:06
浏览 36
已采纳

并发访问无锁变量

I was disturbed by a question,

should we add lock if only one thread write variable, and other thread just read variable?

so I write such code to test it

package main

import (
    "fmt"
    "runtime"
    "sync"
    "time"
)

var lock sync.RWMutex
var i = 0

func main() {
    runtime.GOMAXPROCS(2)
    go func() {
        for {
            fmt.Println("i am here", i)
            time.Sleep(time.Second)
        }
    }()
    for {
        i += 1
    }
}

The result is keep print i am here 0 even after second of time. I know a little about Memory barrier or cpu cache. but how could it be cache for such a long time? I think after a few time, it should read variable I already changed.

Can anyone who is master go or computer system could help answer, please?


Update: i know it is a wrong way to update variable like this, i want to know why it is undefined in cpu/memory view.

  • 写回答

3条回答 默认 最新

  • dongmaxi6763 2018-06-29 03:59
    关注

    finally, i find this answers, i know with a data race you will get a undefined behave, but i want to know why it behave like that currently.

    this snap code is because complier just remove Add function, it never add.

    so we have lesson, if you write a undefined behave, you may got a moon - -

    complier will treat you code as rubbish, it does not have any value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题