According to https://golang.org/ref/spec#Defer_statements there is such an expression: * `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? I have read https://golang.org/ref/mem but got nothing except this. (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 -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/bf1987cf-2c06-46e3-bbc1-be91fb0f11een%40googlegroups.com.