This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: how to cast away 'volatile'?
Sergei Organov <osv@javad.com> writes:
> Ian Lance Taylor <iant@google.com> writes:
> [...]
> > And once you are using a mutex, there is no reason to use volatile.
> > Using volatile will give you no extra protection, it will merely cost
> > you some efficiency.
>
> Yes, that's how it is intended to work. However practice may vary. Some
> time ago there was an interesting example posted in a newsgroup[1].
>
> The initial program was:
>
> for (...) {
> if (...) pthread_mutex_lock(...);
> x = ... x ...
> if (...) pthread_mutex_unlock(...);
> }
>
> and compiler did the following transformation that breaks thread-safety
> ('r' is register):
>
> r = x;
> for (...) {
> if (...) { x = r; pthread_mutex_lock(...); r = x; }
> r = ... r ...
> if (...) { x = r; pthread_mutex_unlock(...); r = x; }
> }
> x = r;
>
> This transformation seems to be OK both from the C language POV and from
> pthread standard POV (though the latter obviously was not intentional),
> but it creates accesses to 'x' outside of the mutex-protected section
> that in turn breaks thread-safety.
>
> Making 'x' volatile would prevent such an optimization in practice,
> isn't it?
That is an interesting example. The question is whether declaring x
volatile would prevent the compiler from moving a load or store to x
across the call to pthread_mutex_lock or pthread_mutex_unlock. I
guess I agree that it would. x must have the correct value when the
functions are called. The use of volatile would ensure that x can
only be read and written once. So there is no way to move the load or
store.
Interesting. Thanks.
Ian