douyi1966 2015-08-12 10:51
浏览 22
已采纳

是否需要同步?

I defined a variable (r.something) inside an object

func (r *Runner) init() {
  r.something = make(map[string]int)
  r.something["a"]=1

  go r.goroutine()
}

while r.goroutine uses value stored in r.something with no synchronization. Nobody else is going to read/write this value except r.goroutine()

Is it safe to do without synchronization?

In other words: I want to reuse some variable from a goroutine initialized somewhere else before goroutine start. Is that safe?

Additional question: After r.goroutine() finishes I want to be able to use r.something from somewhere else(without read/write overlap with other goroutines). Is it safe too?

  • 写回答

3条回答 默认 最新

  • douzhangjian1505 2015-08-12 12:30
    关注

    Of course this is safe, otherwise programming in Go might be a nightmare (or at least much less pleasant). The Go Memory Model is an interesting piece to read.

    The routine creation is a synchronisation point. There is an example very similar to yours:

    var a string
    
    func f() {
        print(a)
    }
    
    func hello() {
        a = "hello, world"
        go f()
    }
    

    With the following comment:

    calling hello will print "hello, world" at some point in the future (perhaps after hello has returned).

    This is because:

    The go statement that starts a new goroutine happens before the goroutine's execution begins.

    The word before is crucial here as it implies routine creation (in one thread) must be synchronised with its start (possibly in other thread), so writes to a must be visible by the new routine.

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

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂