[concurrency-interest] Using a volatile variable as a "guard"

Joe Bowbeer joe.bowbeer at gmail.com
Mon Feb 7 15:45:45 EST 2011

Thanks, Hans.

Between the acquire/release model and the data-race check, I should be able
to keep this straight!

However, even though I was one of the ones pointing out problems in the
volatile spec in 1997 (after Tom May brought it to my attention), and I
really should be capable of using them correctly, I haven't used volatiles
in more than 10 years for anything more than a termination flag.

Whenever I see a volatile today, the only thing I know for certain is: there
be bugs.

So, as a favor to me and others like me, please refrain from using volatile
if there's a clearer way to do it.


On Mon, Feb 7, 2011 at 11:50 AM, Boehm, Hans wrote:

> I personally still think that by far the cleanest way to think about
> whether a variable should be volatile is to ask:
> Does it participate in a data race?  Can one thread be reading or writing
> it while another thread is writing it?  To answer this question use a simple
> interleaved ("sequentially consistent") model in which nothing can be
> reordered.  In VolatileExample below (continuing to assume a single writer)
> x does not participate in a data race, since x is accessed by the reader
> only after it sees v true, and thus the writer must be done.  v can clearly
> participate in a data race, as can factory and isNuclearFactory in the
> original example.
> This does assume that:
> 1) You apply this rule consistently.  If you don't declare v in the example
> below volatile, then the sequentially consistent reasoning I used to argue
> that x doesn't participate in a data race doesn't hold, since I no longer
> have a data-race-free program.
> 2) Library implementers do the same, or at least make sure that library
> APIs are defined such that clients can continue to use sequentially
> consistent reasoning.  Currently, I think that's a goal of nearly all
> standard library APIs, at least in all cases in which reasonable client code
> can tell.  I suspect there are remaining bugs in some of the details.  But
> none of these issues arise in these examples.
> 3) The program is otherwise correct under sequentially consistent
> reasoning.
> Hans
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20110207/5a9350d2/attachment.html>

More information about the Concurrency-interest mailing list