Hi everyone.
Let's say I am to make my own mutex, lets call it lock / unlock.
Then have the following code:
(And please, this is only a very c-looking pseudo-code. Don't bother saying how the code is or what the point of it is. Its just an example in pseudo-code. No smart ass comments, please.)
Code:
struct lock_l l; // Lock
int global; // Global
thread1() {
// Do some local non-essential work
// Enter mutex
lock(&l);
global = 0;
unlock(&l);
// Do some local non essential work.
}
thread2() {
lock(&l);
// Do something with global
unlock(&l);
}
So, thread 1 just sets global to 0.
Thread 2 do some very important calculation on this variable.
Now , what prevents the compiler-optimizer from changing thread1 to this, moving global = 0; outside the lock. :
Code:
thread1() {
global = 0;
// Enter mutex
lock(&l);
unlock(&l);
}
Is this what memory barriers instructions are for? Or this those only for hardware reordering?
How can I be 100% sure the opitimizer will NOT move statements in between my 2 self made mutex-functions, outside them?