* T L <tapir....@gmail.com> [170709 04:56]: > On Friday, July 7, 2017 at 8:42:28 PM UTC+8, Marvin Renich wrote: > > Yes, the go routine establishes a happens-before relationship such that > > x is incremented before y, and the atomic Add of y and Load of y ensure > > that the Load either happens before or after, but not during, the Add. > > But I remember that the "happens-before relationship" is never written down > in any official Go documentation.
Actually, I believe the documentation is specific enough, at least if you accept a reasonable definition of "atomic" as it is used in the documentation of the atomic package. Without atomic operations, a write to memory in one go routine and a read from the same memory in another (without other synchronization) cannot be guaranteed to have any specific behavior at all. Specifically, the read may return garbage that has nothing to do with either the value that was originally in the memory or the value that is being written to the memory. If you are performing atomic writes and reads, this guarantees that the read must either observe the original value or the value placed by the write; no other value may be observed. So, if the initial value of variable X is 0, and the only code that changes variable X is in go routine A, which changes it atomically (exactly one time) to have a value 1, then go routine B, which atomically reads variable X, must either get a value of 0, which implies that the read MUST happen-before the write in go routine A, or it must get a value of 1, which implies that the write in go routine A MUST happen-before the read in go routine B. So, the value read by go routine B can be used to determine which of the read and write happens before the other. In other words, if we take the existing description under "Happens Before" it the memory model documentation, specifically: Also, if e1 does not happen before e2 and does not happen after e2, then we say that e1 and e2 happen concurrently. And we add the following definition, which currently is implicit in the atomic documentation: An atomic read and an atomic write of the same variable cannot happen concurrently [for the definition of "concurrently" above]. Then an atomic read and an atomic write on the same variable establish a happens before relationship between the two, but it is up to the code to be able to prove which one happens first. This is slightly different than most of the other happens-before relationships, such as channel writes and reads, where the operation determines which one happens first, but it is still good enough to establish a happens-before relationship based on the result of the read. ...Marvin -- 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. For more options, visit https://groups.google.com/d/optout.