This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: how to cast away 'volatile'?
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?
[1] See
<http://groups.google.com/group/comp.lang.c++.moderated/msg/554aca62b08f8a21>
for details.
-- Sergei.