Re: C++ Threads, what's the status quo?
Greg Herlihy wrote:
Pete Becker wrote:
Greg Herlihy wrote:
static int count;
// returns true if value was updated
bool CompareAndSwap( long oldValue, long newValue, long *address);
int main()
{
while (true)
{
long n = count;
if ( CompareAndSwap( n, n+1, &count))
break;
}
...
}
There is no guarantee that the compiler won't optimize away 'n' and
simply pick up count's value twice to compute the arguments to
CompareAndSwap, leaving open the possibility that another thread will
modify count between the two accesses.
If a C++ program accesses "count" twice instead of assigning its value
to n once, then it's time to find a better C++ compiler, because the
one that built a program with that behavior - is not very good.
This isn't a discussion about ad-hoc definitions of a "good" compiler,
but about what's required by the standard. A conforming compiler is
allowed to generate code that suppresses n and accesses count twice.
That's one reason why this code doesn't guarantee thread safety.
Nonetheless, declaring n volatile:
int count;
int main()
{
while (true)
{
volatile long n = count;
if ( CompareAndSwap( n, n+1, &count))
break;
}
}
would force the compiler to use a consistent value for n, when
calculating the n and n+1 arguments for the compare-and-swap function
call.
It would require the compiler to write the value of count to n once,
then read the value of n twice. I don't see anything in the standard
that prohibits the compiler from using the value from count, as before,
to compute the arguments in the call to CompareAndSwap.
--
-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]