My multithreaded code is as follows:
thread A
while(true) {
foo();
sleep();
}
thread B
...
bar_off();
bar_on();
...
foo() isn't safe to be executed when bar_off is called and until bar_on has completed.
I could rewrite my code as follows:
int volatile foo_is_safe=0;
thread A
while(true) {
if (foo_is_safe) {
foo();
}
sleep();
}
thread B
...
foo_is_safe=0;
bar_off();
bar_on();
foo_is_safe=1;
...
But I believe this won't work since the compiler is not required to preserve the ordering between setting foo_is_safe and calling the bar_* functions. I am not even sure the compiler will not simply ignore setting foo_is_safe to 0.
Am I correct? What's the proper way to make my code safe, i.e. enforce foo_is_safe is set before bar_off() and after bar_on()?