On Tuesday, September 8, 2015 at 12:40:23 AM UTC-7, enormouspenguin wrote:
On Tuesday, September 8, 2015 at 12:33:30 PM UTC+7, Henrik Johansson wrote:
My understanding is that there are no such guarantees at all. Even
ignoring memory effects there is still a race between the execution of the
two goroutines determined by the scheduler.
As I said, I mostly concern about visibility. I am aware of the race and
know that at the end of main(), A and B could take any value but could each
take an entirely different value from each other (e.g.: A == 20 && B == 10)?
A CAS operation compose of 3 little ops that must execute as a single
transaction: read, compare and write. All atomic functions in Go has
implicit acq_rel semantic (I get it from here
rationale is that because a CAS always have to execute a read first
therefore although it failed at the comparison phase (leading to write not
executed), it should see all side effects prior to the written value that
it observed through the initial read.
I read through the memory model <https://golang.org/ref/mem
> after seeing
this, and my impression was that it implies that this is safe. It says this:
That is, r is guaranteed to observe w if both of the following hold:
w happens before r.
Any other write to the shared variable v either happens before w or after
According to my understanding, we know that *w* happens before the
succeeding CAS, because that is how program order is expressed within a
single goroutine. We also know that the succeeding CAS happens before the
failing CAS. And finally we know that the failing CAS happens before the *r*.
As long as there is no other *w'*, I believe *r* should be guaranteed to
observe the write.
The memory model is not explicit about happens-before relationships between
multiple shared variables. However, I'm not really sure how sync.Mutex
could possibly work if such a relationship didn't exist, since it just uses
atomics under the covers
That said, I didn't post anything last night because I wasn't confident,
and I still am not. I wouldn't rely on behavior like this to work in a
program. I would use mutex. If I needed the performance, I might wait until
someone with more knowledge responded on this post, or read the disassembly
and the manual for my processor until I gained confidence.
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 email@example.com.
For more options, visit https://groups.google.com/d/optout.