force compiler to refresh variable content in specific point

75 views Asked by At

I have a global variable that in most time can't be changed by other thread, but in single point it can.

I want to force the compiler to refresh the registers that holding this global content after that point, but without defining this global to be volatile all the time because it time consuming.

2

There are 2 answers

3
arye On

You can call some dummy function from other file after this point, that will force the compiler to refresh the global because he can't know if the global changed in the dummy function. It is bit not nice code but it will work.

0
nielsen On

Since the global variable is shared and can potentially be modified by more than one thread, it should be declared volatile. It may then be copied to and from a non-volatile variable if it needs to be used for lengthy local processing.

Even if there is currently a way to "fool" the compiler into forcing a true read/write of the variable without declaring it volatile, chances are that at some point compiler optimizers will get even smarter and optimize that construct away.