Re: Need to use "volatile" for accessing variables between threads?
On Jul 27, 6:37 am, Richard Herring <junk@[127.0.0.1]> wrote:
In message
<9fec04a7-3120-490b-8b9d-524a7bc25...@p23g2000vbl.googlegroups.com>,
Virchanza <virt...@lavabit.com> writes
Volatile is intended to be used where a variable's value can
mysteriously change outside of the normal flow of code.
....which is exactly how changes to a variable's value made on one
thread - appear to another thread.
I'm still not sure whether "a separate thread" qualifies as being
mysterious enough. Some people are telling me I need volatile. Others
are telling me I don't need volatile. I don't know who to believe.
You do need "volatile" - but volatile is by itself is not enough to
make your program thread-safe. You will also need some kind of memory
barrier (or some mutual exclusion mechanism).
Is it even possible to get an answer to this question, or is it simply
"undefined"?
The effect of "volatile" is clearly defined- and clearly needed for
any variable whose value can change asynchronously with regard to the
current execution flow.
I'm still not decided.
I think what you're being told is this:
1. volatile doesn't imply atomic access, and therefore it can't
guarantee that another thread won't change a shared variable while
you're half-way through reading it.
True. But the reason why the variable must be declared "volatile" has
nothing to do with assuring exclusive access or, really, anything to
do with threading in particular.
2. Therefore you need some other mechanism to guarantee thread-safe
shared access.
3. Once you have that other mechanism in place, there's no need to use
volatile.
Not so. Declaring a variable "volatile" forces the compiler to load
that variable's value from memory each time that value is needed.
Otherwise - if there are no apparent write operations to the variable
within a given block of code - then the compiler is very likely to
store the variable's value in a register once at the beginning of the
block; and then use the register-based value in subsequent operations
as that variable's current value.
In this case, the value of the variable can change asynchronously with
regard to the current execution flow - and it does not matter how or
why its value may change. To the compiler a value changed by another
thread is just as asynchronous a change as one, say, made by memory-
mapped I/O. And in either case, the "volatile" keyword is needed to
prevent the compiler from caching that variable's value.
Greg