If there are pointers "A" and "B", with a requirement such that any writes to "A" should be made visible before any writes to "B" are made visible. If I am not allowed to use locks and if I am not allowed to declare these variables as "volatile", will the following code guarantee that, the above requirement will be met?
volatile temp;
*A = value1;
temp = *A;
if (temp == value1) {
*B = value2
}
You will want to use memory barriers or fences: see http://en.wikipedia.org/wiki/Memory_barrier
In the Linux kernel you can use the rmb() or wmb() calls.
Under pthreads you can use pthread_barrier_wait(), though that doesn't appear to be in my pthreads manpages.
On MSVC, look at Force order of execution of C statements? - which also has some good general information.
If you find an 'atomic' library, that will normally include barrier functions.
The answer is simple. You cannot. Reordering can happen because:
To force memory ordering you need synchronization. Unfortunately there are tons of approaches here. Each approach has its own pros and cons. Depending on your situation you need to pick some.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With