[concurrency-interest] "Volatile-like" guarantees

Niko Matsakis niko at alum.mit.edu
Thu Feb 3 00:23:08 EST 2011


Brian Goetz wrote:
> I think you've got some things backwards in Foo.  You want to swap the 
> statements in setF, and swap the Wf assignment.  Similarly, you want 
> to swap the statements in getF:
>
>     class Foo {
>         private volatile int v;
>         private int f;
>
>         void setF(int x) {
>             f = x;    // Wf
>             v = 0;    // Wv
>         }
>
>         int getF() {
>             int y = v;    // Rv
>             return f;     // Rf
>         }
>     }
>
> Now, calls to setF happen-before calls to getF, which is the ordering 
> you want to expose.  But additionally, you no longer have a data race 
> on f; the write to f really does happen-before the read of f in 
> another thread:
So, my first instinct was to place the volatile writes/reads in the 
order you show here, but I'm not sure that it provides the proper 
guarantees.  In particular, isn't it possible that in some program run 
Rv synchronizes with Wv, but Rf still sees the write from Wf? In that 
case, the reads that follow Rf would not happen after the writes that 
preceded Wf.

Certainly when using memory barriers/fences, the sequence is traditionally:
     Thread 1. perform dependent writes, memory barrier, perform 
significant write
     Thread 2. perform significant read, memory barrier, perform 
dependent reads
is it not?  I guess the question is to what extent a volatile can be 
used like a memory barrier.



Niko



More information about the Concurrency-interest mailing list