drqyxkzbs21968684 2019-07-01 09:46
浏览 41

具有单个读取器和单个写入器的Golang作业安全

Say I have two go routines:

var sequence int64

// writer
for i := sequence; i < max; i++ {
  doSomethingWithSequence(i)
  sequence = i
}

// reader
for {
  doSomeOtherThingWithSequence(sequence)
}

So can I get by without atomic?

Some potential risks I can think of:

  1. reorder (for the writer, updating sequence happens before doSomething) could happen, but I can live with that.

  2. sequence is not properly aligned in memory so the reader might observe a partially updated i. Running on (recent kernel) linux with x86_64, can we rule that out?

  3. go compiler 'cleverly optimizes' the reader, so the access to i never goes to memory but cached in a register. Is that possible in go?

  4. Anything else?

  • 写回答

1条回答 默认 最新

  • dpdyh86002 2019-07-01 13:23
    关注

    Go's motto: Do not communicate by sharing memory; instead, share memory by communicating. Which is an effective best-practice most of the time.

    1. If you care about ordering, you care about synchronizing the two goroutines.
    2. I don't think they are possible. Anyway, those are not things you should worry about if you properly design the synchronization.
    3. The same as above.

    Luckily, Go has a data race detector integrated. Try to run your example with go run -race. You will probably see the race condition happening on sequence variable.

    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算