3 ms·
> won't guarantee that some other thread of execution won't change the value under your nose My understanding is that compilers can always assume that there is
by rrss 7y ago
> won't guarantee that some other thread of execution won't change the value under your nose
My understanding is that compilers can always assume that there is no other thread involved, which (part of) why C11 atomics are necessary. Is that not the case?
- H8crilA 7y agoYup, it's a data race (and therefore UB) to access the same memory from two different threads without synchronizing instructions (like mutexes, thread start/join, atomics). It is allowed to concurrently read from const regions. But not concurrently read and write, and definitely not concurrently write.
- alexlarsson 7y agoYes, but it can't assume any random function call it does doesn't use a different pointer to the same object which is not const. So, even if you don't cast const to non-const pointers you can run into the const value changing.
- bstamour 7y agoConcrete example: void foo(const int* const p1, int* const p2) { int a = *p1; *p2 += 42; int b = *p1; return a == b; // b = a + 42 } int main() { int x = 0; return foo(&x, &x); }
- bstamour 7y agoYou're right, but what I meant about it was that just because the variable is const, doesn't mean it can't change from somewhere else between reads. Even if you use synchronization to avoid data races, if you read the pointer to const twice in the function, it could change between the reads.
- SAI_Peregrinus 7y agoThe most common example of that is probably a const volatile variable for the input data register of some peripheral. New data can come in at any time, and writes do nothing.