具有单个读取器和单个写入器的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?

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.