> This is the precise optimization that 'volatile' inhibits.

For single-threaded code, you are right. But we are talking about 
multi-threaded code.

> 'volatile'
> requires that the value not be cached in "cheap-to-access" locations
> like registers, instead being re-loaded from "expensive-to-access"
> locations like the original memory -- because it may be changed from
> outside the control flow that the compiler knows about.

I had this exact same argument a long time ago about code like this:

int foo;
volatile int have_pointer=0;
volatile int *pointer=NULL;

In one thread:
pointer=&foo;
have_pointer=1;

In another:
if(have_pointer!=0) *pointer++;

All I could say was that this code breaks the standard. One thread accesses 
'have_pointer' while another thread might be modifying it. Did I know how it 
could fail? No. In fact, nobody could think of a way it could fail because we 
didn't really realize that the ordering could break and not just the concurrent 
access/modification.

Did it fail? Yes. I believe we first had faults on new UltraSparc CPUs (might 
have been new Alphas, I can't remember for sure). It was a classic case of 
"worked on old CPUs, failed on new ones". The new ones had some write 
reordering capability.

If you look at Itanium compilers, you will see that they don't put memory 
barriers between 'volatile' accesses. So 'volatile' does not provide ordering. 
It is known not to provide atomicity. There are platforms where a 'uint64_t' 
*can't* be written atomically, so what's a read of a volatile 'uint64_t' even 
supposed to do?

So you have to be saying, "you don't get atomicity or ordering, but you do get 
..." What exactly? And what standard says so? My copy of the pthreads standard 
says that accessing a variable in one thread while another thread is or might 
be modifying it is undefined behavior.

IMO, "it may break on a new CPU" is totally unacceptable for code that is going 
to be distributed and especially for libraries with expected wide distribution.

DS

PS: There are many, many more stories of "I couldn't think of any way it could 
break" code breaking when the real world thought of ways. You have to code 
based on guarantees in standards, not your own lack of imagination.


______________________________________________________________________
OpenSSL Project                                 http://www.openssl.org
Development Mailing List                       openssl-dev@openssl.org
Automated List Manager                           [EMAIL PROTECTED]

Reply via email to