3 ms·
If the programmer really needs reads and writes through particular pointers to happen in a particular sequence, because the target memory follows different rule
by anderskaseorg 6y ago
If the programmer really needs reads and writes through particular pointers to happen in a particular sequence, because the target memory follows different rules than the language ordinarily allows the compiler to assume, then it’s the programmer’s responsibility to use the annotation provided by the language for exactly that purpose: volatile. If the compiler had to assume that every pointer needs to be treated as volatile, just about all generated code would be be slowed down dramatically.
As for locks, the language already has rules about which memory access are allowed to be reordered across lock acquire and release calls. Otherwise locks wouldn’t work correctly at all.
- SAI_Peregrinus 6y agoTo be extra pedantic, that's not what volatile does. Volatile ensures that access through the variable must behave strictly according to the rules of the C abstract machine, but the definition of access is implementation defined. A compiler author could define "access" to be "reads from the variable" or "writes to the variable", or neither, and make the entire keyword useless. As long as they document that somewhere, it's compliant with the standard. You think it means "reads and writes" but it doesn't have to. It's tempting to write a "malicious compliance C compiler" that complies with the standard but makes all the most perverse possible choices.
- klodolph 6y agoYour comment is technically correct, but the original description of “volatile” in the parent comment is much clearer. It may be fun to imagine what would happen if the compiler writer were malicious, but it doesn’t really help us understand C. Just like C compilers assume that the program is correct, the writers of the C standard assume that the people reading it are not insane or malicious.
- Dylan16807 6y ago> A compiler author could define "access" to be "reads from the variable" or "writes to the variable", or neither, and make the entire keyword useless. As long as they document that somewhere, it's compliant with the standard. Nobody is going to accept that as a compliant implementation.