Chapter: Multicore Application Programming For Windows, Linux, and Oracle Solaris - Hand-Coded Synchronization and Sharing

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Volatile Variables

It should be apparent from the previous discussions that the volatile keyword is useful in the context of multithreaded code but does not stop the compiler from reordering operations.

Volatile Variables

 

It should be apparent from the previous discussions that the volatile keyword is useful in the context of multithreaded code but does not stop the compiler from reordering operations. The volatile keyword just tells the compiler to reload variables from mem-ory before using them and store them back to memory after they have been modified. This behavior imposes an overhead on the access of any volatile variables. They must be held in memory and cannot be cached in a variable.

 

Using the volatile keyword is necessary to avoid undesirable caching, in registers, of the values held in memory locations. However, the keyword also stops desirable caching of the variable, so any use of the variable can be expensive.

 

It may be possible to reduce this cost by typecasting the variable to be volatile or using function calls that would cause the compiler to believe that the variable might have been modified.

 

However, it should be observed that judicious use of compiler memory barriers can be low cost and a more accurate way of ensuring that variables are stored back to mem-ory and reloaded from memory at the desired point in the code. Listing 8.14 modifies the code shown in Listing 8.6 to avoid having to declare the variable start as volatile and instead uses a compiler barrier to ensure that the value is reloaded from memory.

 

Listing 8.14   Code Where Compiler Barrier Ensures Reloading of Variable start

extern int start;

 

void waitforstart()

 

{

while(start==0) { asm volatile( "": : : "memory" ); }

 

}


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.