I've seen this sentence:
the general rule is, if you have variables of primitive type that must be shared among multiple threads, declare those variables volatile
from this article, and this sentence:
In general, any data that may be undated asynchronously should be declared to be volatile.
from this page, now considering this introduced rule I'd like to know could you bring an example of a case where despite existence of asynchronous access to a data declaring that data volatile has no use in practice or there's no such exceptional case and the rule is strict.
I would propose a considerably more strict but very useful rule: if you do not understand exactly what
volatile
does, do not use it. Instead, uselock
. If you do not understand exactly whatlock
does and how to use it, do not use multithreading.I remember when that article was published and I remember the endless discussions that then followed on comp.lang.c++.moderated.
IIRC, Andrei hijacks the
volatile
keyword to use it to discriminate between different function overloads. (See this article by Scott Meyers for another such an idea.) What he does is brilliant, in that it allows the compiler to catch you if you mess up protected and unprotected access to objects (very much like the compiler catches you should you try to modify a constant). But besides the fact that it helps you, it has nothing to do with actually protecting concurrent access to objects.The problem is only that 90% of the people have one glance at the article and all they see is
volatile
and "threads" in the same article. Depending on their knowledge, they then either draw the wrong conclusion thatvolatile
is good for threads (you seem to have done so) or they yell at him for leading others to draw the wrong conclusions.Very few people seem to be able to actually read the article thoroughly and understand what he really does.