`A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns`
Does `defer` ensure happens-before behaviour with non-defer code?
(It seems not clear to me about the meaning of `the order expressed by the program`.)
`Within a single goroutine, the happens-before order is the order expressed by the program.`
In following case what I know is ③ happens before ①,
but what about ②? Is it possible that ② is executed after
③ and ①?
```Go
var A, B, C int
func main() {
defer func() { A = 4 } //①
B = 5 //②
defer func() { C = 6 } //③
}
```
Appendix:
1. The background:
I was digging into the implementation of sync.Once and
wonder if `defer atomic.StoreUint32(&o.done, 1)` in
function doSlow could be replaced with `defer func() {o.done = 1}`.
```
func (o *Once) Do(f func()) {
if atomic.LoadUint32(&o.done) == 0 {
o.doSlow(f)
}
}
func (o *Once) doSlow(f func()) {
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}
```
2. As I know, `defer` is implemented by inserting corresponding
function calling before any exiting point(Eg. in x86 the ret instruction).
However x86 allows out-of-order execution happening across function calls,
and I'm not sure if it will happen in this case(f() and o.done has no dependency
with each other so it is possible?).
If anyone knows I would appreciate for your clarification.
Thanks for your time.
Ge